Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): execute behavior regressions and preserve Windows runner arguments
MagicLizi9c7220ff53a7
diff --git a/apps/desktop/src/main/__tests__/authCredentialStoreHealth.contract.test.ts b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.contract.test.tsnew file mode 100644index 0000000000..1109a71dff--- /dev/null+++ b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.contract.test.ts@@ -0,0 +1,100 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++describe("authManager credential-store escalation wiring", () => {++ const authSource = readFileSync(+ resolve(process.cwd(), 'src/main/authManager.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+++ it('retains startup failure across all owner cleanup paths and exposes it before loading providers', () => {+ const recovery = authSource.slice(+ authSource.indexOf('async function withAccountFreeOwnerCommit'),+ authSource.indexOf('interface CloudOwnerDataReservation'),+ );+ // Passive, normal commit and failed cleanup must all retain the same cause.+ expect(+ recovery.match(/credentialStoreUnavailable: opts\.credentialStoreUnavailable/g),+ ).toHaveLength(3);+ expect(recovery).toContain(+ 'if (credentialStoreUnavailable) credentialStoreHealth.noteStartupFailure();',+ );+ const clear = authSource.slice(+ authSource.indexOf('function clearAuth('),+ authSource.indexOf('// ── Public API'),+ );+ expect(clear.indexOf('credentialStoreHealth.noteStartupFailure()')).toBeGreaterThan(+ clear.indexOf('credentialStoreHealth.reset()'),+ );+ const login = authSource.slice(+ authSource.indexOf('export async function getLoginState()'),+ authSource.indexOf('async function completeLogin('),+ );+ expect(login.indexOf('credentialStoreHealth.unavailable')).toBeLessThan(+ login.indexOf('await loadLoginProviders'),+ );+ expect(login).toContain(+ "state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' }",+ );+ });+++ it('transient-unreadable 分支喂失败计数并在翻转时广播,但仍保持瞬时语义', () => {+ const start = authSource.indexOf('export async function refresh(): Promise<boolean> {');+ const end = authSource.indexOf('const diskTokenChangedBeforeRefresh', start);+ const body = authSource.slice(start, end);++ // 升级钩子必须在 transient 分支内、且仍然 return false + 重排重试+ // (升级不改变「不强踢用户」的语义,只是多了状态广播)。+ expect(body).toContain('credentialStoreHealth.noteReadFailure()');+ const noteIdx = body.indexOf('credentialStoreHealth.noteReadFailure()');+ expect(noteIdx).toBeGreaterThan(body.indexOf('treating as transient'));+ // 注意 refresh body 更早处(realm manifest 分支)也调用了同名重排函数,+ // 必须取 noteReadFailure 之后的那一次。+ const retryAfterNote = body.indexOf('scheduleRefreshRetryAfterTransientFailure(refreshEpoch);', noteIdx);+ expect(retryAfterNote).toBeGreaterThan(noteIdx);+ // 升级不改变瞬时语义:transient 分支内不得出现实际的过期 / 清态调用+ // (匹配调用形态,避免误中提及函数名的注释)。+ const transientBranch = body.slice(body.indexOf('treating as transient'), retryAfterNote);+ expect(transientBranch).not.toContain('await expireRuntimeAuth(');+ expect(transientBranch).not.toContain('clearAuth(');+ });+++ it('成功读到持久会话时喂恢复并在翻转时广播', () => {+ const start = authSource.indexOf('export async function refresh(): Promise<boolean> {');+ const end = authSource.indexOf('const diskTokenChangedBeforeRefresh', start);+ const body = authSource.slice(start, end);+ expect(body).toContain(+ 'if (persistedSession !== null && credentialStoreHealth.noteRecovered())',+ );+ });+++ it('clearAuth 整体清态时复位状态机', () => {+ const start = authSource.indexOf('function clearAuth(');+ const end = authSource.indexOf('commitActiveAppSession', start);+ const body = authSource.slice(start, end);+ expect(body).toContain('credentialStoreHealth.reset();');+ });+++ it('AuthState 快照携带 credentialStoreUnavailable,登出投影恒为 false', () => {+ const snapStart = authSource.indexOf('function snapshotAuthState(): AuthState {');+ const snapEnd = authSource.indexOf('function snapshotLoggedOutAuthState', snapStart);+ expect(authSource.slice(snapStart, snapEnd)).toContain(+ 'credentialStoreUnavailable: credentialStoreHealth.unavailable',+ );+ const loggedOutStart = snapEnd;+ const loggedOutEnd = authSource.indexOf('function notifyRenderer', loggedOutStart);+ expect(authSource.slice(loggedOutStart, loggedOutEnd)).toContain(+ 'credentialStoreUnavailable: false',+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.tsindex dc09a7b52c..fa8df2033b 100644--- a/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts+++ b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts@@ -101,7 +101,7 @@ describe('authManager credential-store escalation wiring', () => {const expression = authSource.match(/'cold-start-credential-reconcile-unavailable',\s*([\s\S]*?),\s*\);/,)?.[1];- expect(expression).toBeDefined();+ if (!expression) throw new Error('Credential reconciliation classifier was not found');class AuthApiError extends Error {constructor(public code: string) {super(code);@@ -125,7 +125,7 @@ describe('authManager credential-store escalation wiring', () => {const body = authSource.match(/function hasPotentiallyPersistedAuthCredentials\(\): boolean \{([\s\S]*?)\n\}/,)?.[1];- expect(body).toBeDefined();+ if (!body) throw new Error('Persisted credential probe was not found');const keys = ['AUTH_SESSION_KEY','AUTH_ACCOUNT_VAULT_KEY',@@ -162,85 +162,4 @@ describe('authManager credential-store escalation wiring', () => {expect(probe(null, 'EPERM')).toBe(true);expect(probe(null, 'EIO')).toBe(true);});-- it('retains startup failure across all owner cleanup paths and exposes it before loading providers', () => {- const recovery = authSource.slice(- authSource.indexOf('async function withAccountFreeOwnerCommit'),- authSource.indexOf('interface CloudOwnerDataReservation'),- );- // Passive, normal commit and failed cleanup must all retain the same cause.- expect(- recovery.match(/credentialStoreUnavailable: opts\.credentialStoreUnavailable/g),- ).toHaveLength(3);- expect(recovery).toContain(- 'if (credentialStoreUnavailable) credentialStoreHealth.noteStartupFailure();',- );- const clear = authSource.slice(- authSource.indexOf('function clearAuth('),- authSource.indexOf('// ── Public API'),- );- expect(clear.indexOf('credentialStoreHealth.noteStartupFailure()')).toBeGreaterThan(- clear.indexOf('credentialStoreHealth.reset()'),- );- const login = authSource.slice(- authSource.indexOf('export async function getLoginState()'),- authSource.indexOf('async function completeLogin('),- );- expect(login.indexOf('credentialStoreHealth.unavailable')).toBeLessThan(- login.indexOf('await loadLoginProviders'),- );- expect(login).toContain(- "state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' }",- );- });-- it('transient-unreadable 分支喂失败计数并在翻转时广播,但仍保持瞬时语义', () => {- const start = authSource.indexOf('export async function refresh(): Promise<boolean> {');- const end = authSource.indexOf('const diskTokenChangedBeforeRefresh', start);- const body = authSource.slice(start, end);-- // 升级钩子必须在 transient 分支内、且仍然 return false + 重排重试- // (升级不改变「不强踢用户」的语义,只是多了状态广播)。- expect(body).toContain('credentialStoreHealth.noteReadFailure()');- const noteIdx = body.indexOf('credentialStoreHealth.noteReadFailure()');- expect(noteIdx).toBeGreaterThan(body.indexOf('treating as transient'));- // 注意 refresh body 更早处(realm manifest 分支)也调用了同名重排函数,- // 必须取 noteReadFailure 之后的那一次。- const retryAfterNote = body.indexOf('scheduleRefreshRetryAfterTransientFailure(refreshEpoch);', noteIdx);- expect(retryAfterNote).toBeGreaterThan(noteIdx);- // 升级不改变瞬时语义:transient 分支内不得出现实际的过期 / 清态调用- // (匹配调用形态,避免误中提及函数名的注释)。- const transientBranch = body.slice(body.indexOf('treating as transient'), retryAfterNote);- expect(transientBranch).not.toContain('await expireRuntimeAuth(');- expect(transientBranch).not.toContain('clearAuth(');- });-- it('成功读到持久会话时喂恢复并在翻转时广播', () => {- const start = authSource.indexOf('export async function refresh(): Promise<boolean> {');- const end = authSource.indexOf('const diskTokenChangedBeforeRefresh', start);- const body = authSource.slice(start, end);- expect(body).toContain(- 'if (persistedSession !== null && credentialStoreHealth.noteRecovered())',- );- });-- it('clearAuth 整体清态时复位状态机', () => {- const start = authSource.indexOf('function clearAuth(');- const end = authSource.indexOf('commitActiveAppSession', start);- const body = authSource.slice(start, end);- expect(body).toContain('credentialStoreHealth.reset();');- });-- it('AuthState 快照携带 credentialStoreUnavailable,登出投影恒为 false', () => {- const snapStart = authSource.indexOf('function snapshotAuthState(): AuthState {');- const snapEnd = authSource.indexOf('function snapshotLoggedOutAuthState', snapStart);- expect(authSource.slice(snapStart, snapEnd)).toContain(- 'credentialStoreUnavailable: credentialStoreHealth.unavailable',- );- const loggedOutStart = snapEnd;- const loggedOutEnd = authSource.indexOf('function notifyRenderer', loggedOutStart);- expect(authSource.slice(loggedOutStart, loggedOutEnd)).toContain(- 'credentialStoreUnavailable: false',- );- });});diff --git a/apps/desktop/src/main/__tests__/authHostedCallback.contract.test.ts b/apps/desktop/src/main/__tests__/authHostedCallback.contract.test.tsnew file mode 100644index 0000000000..e05a11496c--- /dev/null+++ b/apps/desktop/src/main/__tests__/authHostedCallback.contract.test.ts@@ -0,0 +1,117 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * 分流形态的源码守卫(同 authLoginFlowReset.test.ts 的既有做法):+ * openSystemBrowserAuthorization 未导出,且两条分支各自依赖 Electron 与网络,+ * 集成测试代价过高;而"清单为空必须回落 loopback"是本次改动对现网用户的核心+ * 承诺——写反方向会让所有人登录不了,值得单独钉住。+ */+describe('openSystemBrowserAuthorization 分流', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(+ /\r\n/g,+ '\n',+ );++ it('按本次登录区域的端点清单分流,空值回落 loopback(默认关闭)', () => {+ const start = source.indexOf('async function openSystemBrowserAuthorization(');+ expect(start).toBeGreaterThan(-1);+ const body = source.slice(start, source.indexOf('\n}', start));++ expect(body).toContain('client: CindyAuthClient');+ expect(body).toContain('loginRealm: AuthRegion');+ expect(body).not.toContain('pendingAuthRealm ?? activeAuthRealm');+ expect(body).toContain(+ "getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl')",+ );+ // 三元方向:非空 → hosted,空 → loopback。写反即所有存量用户登录中断。+ expect(body).toContain('? openHostedBrowserAuthorization(');+ expect(body).toContain(': openLoopbackBrowserAuthorization(');+ });++ it('authorize、callback 与轮询复用 action 冻结的 auth client', () => {+ const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');+ const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));+ const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');+ const loopbackBody = source.slice(+ loopbackStart,+ source.indexOf('\n}\n\n// ── Refresh scheduling', loopbackStart),+ );+ const actionStart = source.indexOf('async function runLoginAction(');+ expect(actionStart).toBeGreaterThan(-1);+ const actionBody = source.slice(+ actionStart,+ source.indexOf('\n}\n\nexport async function dispatchLoginAction', actionStart),+ );++ expect(hostedBody).toContain('client: CindyAuthClient');+ expect(hostedBody).toContain('client.buildAuthorizeUrl(');+ expect(hostedBody).not.toContain('createAuthClient()');+ expect(loopbackBody).toContain('client: CindyAuthClient');+ expect(loopbackBody).toContain('client.buildAuthorizeUrl(');+ expect(loopbackBody).not.toContain('createAuthClient()');+ expect(actionBody).toContain('const client = createAuthClient(loginRealm);');+ expect(actionBody).toContain(+ 'openSystemBrowserAuthorization(\n client,\n loginRealm,',+ );+ expect(actionBody).toContain('client.exchangeAuthorizationCode(');+ });++ /**+ * 取回凭据必须与走浏览器的 state 分离。写回 input.state 会让任何能读浏览历史的+ * 扩展 / 同机进程抢先消费掉一次性结果,把真实客户端顶成 expired。+ */+ /**+ * 唤起浏览器这一步发生在轮询开始之前,若只是 await 它,取消信号与五分钟预算都够+ * 不着——shell.openExternal 在系统默认浏览器冷启动等情况下可能长时间不返回。+ */+ it('唤起浏览器与取消/超时竞速,并从同一份预算里扣时间', () => {+ const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');+ const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));++ expect(hostedBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), signal)');+ expect(hostedBody).toContain('if (!launched.opened) return { error: launched.error };');+ const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');+ const loopbackBody = source.slice(loopbackStart, source.indexOf('\n}\n', loopbackStart));+ expect(loopbackBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), launchCancellation.signal)');+ expect(loopbackBody).toContain('launchCancellation.abort();');+ // 不能是裸 await:那样取消与超时都落不到这一步上+ expect(hostedBody).not.toMatch(/await shell\.openExternal\(authUrl\);/);+ // 轮询预算要扣掉唤起已花的时间,整次尝试仍是一个五分钟+ expect(hostedBody).toContain('deadline - Date.now()');+ });++ it('轮询用的是 pollSecret,不是会进浏览器的 state', () => {+ const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');+ const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));++ expect(hostedBody).toContain('createDesktopPollCredentials()');+ expect(hostedBody).toContain('pollDesktopAuthorization(pollSecret');+ // authorize 收到的必须是哈希后的 clientState,而不是原像+ expect(hostedBody).toContain('state: clientState');+ expect(hostedBody).not.toContain('pollDesktopAuthorization(input.state');+ });++ it('托管链路不落地本地监听,loopback 链路保持原样', () => {+ const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');+ expect(hostedStart).toBeGreaterThan(-1);+ const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));+ // 先钉住切片真的取到了函数体,否则下面两条 not.toContain 会在空串上假通过。+ expect(hostedBody).toContain('runHostedCallbackPolling({');+ expect(hostedBody).toContain('shell.openExternal(authUrl)');+ // 托管链路整个不碰本地 HTTP server —— 这正是它绕开 IP 暴露的前提。+ expect(hostedBody).not.toContain('createServer(');+ expect(hostedBody).not.toContain('127.0.0.1');++ // loopback 链路仍是那台随机端口监听,回退路径没有被顺手改掉。+ const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');+ expect(loopbackStart).toBeGreaterThan(-1);+ const loopbackBody = source.slice(loopbackStart);+ expect(loopbackBody).toContain("server.listen(0, '127.0.0.1'");+ expect(loopbackBody).toContain('http://127.0.0.1:${address.port}/auth/callback');+ });+});diff --git a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts b/apps/desktop/src/main/__tests__/authHostedCallback.test.tsindex 698b1af6df..60b962b714 100644--- a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts+++ b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';@@ -249,114 +247,3 @@ describe('runHostedCallbackPolling', () => {).resolves.toEqual({ code: 'auth-code' });});});--/**- * 分流形态的源码守卫(同 authLoginFlowReset.test.ts 的既有做法):- * openSystemBrowserAuthorization 未导出,且两条分支各自依赖 Electron 与网络,- * 集成测试代价过高;而"清单为空必须回落 loopback"是本次改动对现网用户的核心- * 承诺——写反方向会让所有人登录不了,值得单独钉住。- */-describe('openSystemBrowserAuthorization 分流', () => {- const source = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(- /\r\n/g,- '\n',- );-- it('按本次登录区域的端点清单分流,空值回落 loopback(默认关闭)', () => {- const start = source.indexOf('async function openSystemBrowserAuthorization(');- expect(start).toBeGreaterThan(-1);- const body = source.slice(start, source.indexOf('\n}', start));-- expect(body).toContain('client: CindyAuthClient');- expect(body).toContain('loginRealm: AuthRegion');- expect(body).not.toContain('pendingAuthRealm ?? activeAuthRealm');- expect(body).toContain(- "getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl')",- );- // 三元方向:非空 → hosted,空 → loopback。写反即所有存量用户登录中断。- expect(body).toContain('? openHostedBrowserAuthorization(');- expect(body).toContain(': openLoopbackBrowserAuthorization(');- });-- it('authorize、callback 与轮询复用 action 冻结的 auth client', () => {- const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');- const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));- const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');- const loopbackBody = source.slice(- loopbackStart,- source.indexOf('\n}\n\n// ── Refresh scheduling', loopbackStart),- );- const actionStart = source.indexOf('async function runLoginAction(');- expect(actionStart).toBeGreaterThan(-1);- const actionBody = source.slice(- actionStart,- source.indexOf('\n}\n\nexport async function dispatchLoginAction', actionStart),- );-- expect(hostedBody).toContain('client: CindyAuthClient');- expect(hostedBody).toContain('client.buildAuthorizeUrl(');- expect(hostedBody).not.toContain('createAuthClient()');- expect(loopbackBody).toContain('client: CindyAuthClient');- expect(loopbackBody).toContain('client.buildAuthorizeUrl(');- expect(loopbackBody).not.toContain('createAuthClient()');- expect(actionBody).toContain('const client = createAuthClient(loginRealm);');- expect(actionBody).toContain(- 'openSystemBrowserAuthorization(\n client,\n loginRealm,',- );- expect(actionBody).toContain('client.exchangeAuthorizationCode(');- });-- /**- * 取回凭据必须与走浏览器的 state 分离。写回 input.state 会让任何能读浏览历史的- * 扩展 / 同机进程抢先消费掉一次性结果,把真实客户端顶成 expired。- */- /**- * 唤起浏览器这一步发生在轮询开始之前,若只是 await 它,取消信号与五分钟预算都够- * 不着——shell.openExternal 在系统默认浏览器冷启动等情况下可能长时间不返回。- */- it('唤起浏览器与取消/超时竞速,并从同一份预算里扣时间', () => {- const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');- const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));-- expect(hostedBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), signal)');- expect(hostedBody).toContain('if (!launched.opened) return { error: launched.error };');- const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');- const loopbackBody = source.slice(loopbackStart, source.indexOf('\n}\n', loopbackStart));- expect(loopbackBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), launchCancellation.signal)');- expect(loopbackBody).toContain('launchCancellation.abort();');- // 不能是裸 await:那样取消与超时都落不到这一步上- expect(hostedBody).not.toMatch(/await shell\.openExternal\(authUrl\);/);- // 轮询预算要扣掉唤起已花的时间,整次尝试仍是一个五分钟- expect(hostedBody).toContain('deadline - Date.now()');- });-- it('轮询用的是 pollSecret,不是会进浏览器的 state', () => {- const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');- const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));-- expect(hostedBody).toContain('createDesktopPollCredentials()');- expect(hostedBody).toContain('pollDesktopAuthorization(pollSecret');- // authorize 收到的必须是哈希后的 clientState,而不是原像- expect(hostedBody).toContain('state: clientState');- expect(hostedBody).not.toContain('pollDesktopAuthorization(input.state');- });-- it('托管链路不落地本地监听,loopback 链路保持原样', () => {- const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');- expect(hostedStart).toBeGreaterThan(-1);- const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));- // 先钉住切片真的取到了函数体,否则下面两条 not.toContain 会在空串上假通过。- expect(hostedBody).toContain('runHostedCallbackPolling({');- expect(hostedBody).toContain('shell.openExternal(authUrl)');- // 托管链路整个不碰本地 HTTP server —— 这正是它绕开 IP 暴露的前提。- expect(hostedBody).not.toContain('createServer(');- expect(hostedBody).not.toContain('127.0.0.1');-- // loopback 链路仍是那台随机端口监听,回退路径没有被顺手改掉。- const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');- expect(loopbackStart).toBeGreaterThan(-1);- const loopbackBody = source.slice(loopbackStart);- expect(loopbackBody).toContain("server.listen(0, '127.0.0.1'");- expect(loopbackBody).toContain('http://127.0.0.1:${address.port}/auth/callback');- });-});diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.tsnew file mode 100644index 0000000000..6a67124fba--- /dev/null+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts@@ -0,0 +1,1163 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/** Regression guard for login progress that is intentionally owned by Electron main. */+describe('auth login-flow reset', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(+ /\r\n/g,+ '\n',+ );+ const logoutPolicySource = readFileSync(+ resolve(process.cwd(), 'src/main/authAccountLogoutPolicy.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const deviceLinkSource = readFileSync(+ resolve(process.cwd(), 'src/main/device-link/index.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const hookControlSource = readFileSync(+ resolve(process.cwd(), 'src/main/hook-control/ipc.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('clears renderer state, provider cache, and private tickets whenever auth is cleared', () => {+ const resetStart = source.indexOf('function resetLoginFlowState(): void {');+ const resetEnd = source.indexOf('\n}', resetStart);+ const resetBody = source.slice(resetStart, resetEnd);+ expect(resetBody).toContain('loginFlowState = null;');+ expect(resetBody).toContain('providerConfig = null;');+ expect(resetBody).toContain('discoveredMethods = [];');+ expect(resetBody).toContain('pendingAccountToken = null;');+ expect(resetBody).toContain('pendingLoginTicket = null;');+ expect(resetBody).toContain('pendingBindTicket = null;');+ expect(resetBody).toContain('pendingSsoVerificationTicket = null;');++ const clearStart = source.indexOf('function clearAuth(');+ const clearEnd = source.indexOf('\n}\n\n// ── Public API', clearStart);+ const clearBody = source.slice(clearStart, clearEnd);+ expect(clearBody).toContain('resetLoginFlowState();');+ expect(clearBody).toContain('canaryFlagStore.clear();');+ });++ it('keeps successful personal credentials private until the region choice and excludes saved-account activation', () => {+ const start = source.indexOf('async function finishFreshLogin(');+ const finish = source.slice(start, source.indexOf('async function runLoginAction(', start));+ expect(finish).toContain('discoverPersonalLoginOrganization(outcome.membership');+ expect(finish.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)')).toBeGreaterThan(finish.indexOf('await discoverPersonalLoginOrganization'));+ expect(finish).toContain('pendingPersonalLogin = { outcome, realm: personalRealm }');+ expect(finish).toContain('personalLoginAvailable: true');+ expect(finish).not.toContain('pendingAuthRealm = discovery.region');+ expect(finish).toContain('return completeLogin(outcome, expectedLoginFlowEpoch)');+ const lookupStart = source.indexOf('async function lookupOrganizationRealm(');+ const lookup = source.slice(lookupStart, source.indexOf('async function completeLogin(', lookupStart));+ expect(lookup).not.toContain('pendingAuthRealm =');+ const continueStart = source.indexOf("if (action.type === 'cancel-sso-realm')");+ const continueBody = source.slice(continueStart, source.indexOf('if (!providerConfig)', continueStart));+ expect(continueBody).toContain('pendingAuthRealm = personal.realm');+ expect(continueBody).toContain('await completeLogin(personal.outcome, actionLoginFlowEpoch)');+ expect(continueBody).not.toContain('finishFreshLogin(');+ const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm')");+ const confirmBody = source.slice(confirmStart, continueStart);+ expect(confirmBody.indexOf('pendingPersonalLogin = null')).toBeLessThan(confirmBody.indexOf('pendingAuthRealm = confirmation.targetRegion'));+ expect(confirmBody).toContain('pendingAccountRefreshToken = null');+ expect(source.slice(0, source.indexOf('async function acceptLoginOutcome('))).not.toContain('await finishFreshLogin(');+ expect(source).toContain("await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch)");+ const reset = source.slice(source.indexOf('function resetLoginFlowState()'), source.indexOf('function clearAuth('));+ expect(reset).toContain('pendingPersonalLogin = null');+ expect(reset).toContain('handledLoginEmail = null');+ });++ it('keeps the login-epoch guard and does not resurrect the legacy feishu token chain', () => {+ const completeStart = source.indexOf('async function completeLogin(');+ const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ const completeBody = source.slice(completeStart, completeEnd);+ expect(completeBody).toContain(+ 'if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch)',+ );+ expect(completeBody).toContain('notifyRenderer();');+ // 防复活:主机飞书 token 链已随 refresh-feishu 退役(2026-07-17),+ // authManager 不得再接 FeishuTokenManager(飞书授权归 xd-feishu 意识+ // 的 OAuth broker 通道)。+ expect(source).not.toContain('getFeishuService');+ expect(source).not.toContain('setJwt(');+ });++ it('requires confirmation only when enterprise discovery crosses the build region', () => {+ const start = source.indexOf("if (action.type === 'discover-sso-org') {");+ expect(start).toBeGreaterThan(-1);+ const body = source.slice(+ start,+ source.indexOf("\n if (action.type === 'request-code')", start),+ );+ expect(body).toContain('const methods = ssoOrgDiscoveryToMethods(discovery)');+ expect(body).toContain('if (discovery.region !== AUTH_REGION)');+ expect(body).toContain("type: 'realm-switch-required'");+ expect(body).toContain("type: 'discovery-loaded'");+ expect(body).toContain("email: ''");+ // 唯一 SSO 不在 main 里套 start-browser:否则 renderer 要等整段浏览器+ // 授权结束才拿得到下一步,确认框会卡住。waiting 投影归 renderer。+ expect(body).not.toContain('soleAutoStartSsoMethod');+ expect(body).not.toContain("type: 'start-browser'");++ // 跨区连接只有 confirm action 才写入 start-browser 白名单;弹窗阶段不能+ // 通过伪造 connectionId 直接跳过确认。+ const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm') {");+ const confirmBody = source.slice(+ confirmStart,+ source.indexOf("\n if (action.type === 'cancel-sso-realm')", confirmStart),+ );+ expect(confirmBody).toContain('discoveredMethods = confirmation.methods;');+ expect(confirmBody).toContain("type: 'discovery-loaded'");+ expect(confirmBody).not.toContain('soleAutoStartSsoMethod');+ expect(confirmBody).not.toContain("type: 'start-browser'");+ });++ it('pins personal login to the build realm and clears stale realm before organization discovery', () => {+ const discoveryStart = source.indexOf('async function discoverOrganizationRealm(');+ const discoveryBody = source.slice(discoveryStart, source.indexOf('\n}', discoveryStart));+ expect(discoveryBody).toContain('pendingAuthRealm = null;');++ const actionStart = source.indexOf('async function runLoginAction(');+ expect(actionStart).toBeGreaterThan(-1);+ const actionPreamble = source.slice(+ actionStart,+ source.indexOf('const stateBeforeAction', actionStart),+ );+ expect(actionPreamble).toContain("action.type === 'discover'");+ expect(actionPreamble).toContain("action.type === 'request-code'");+ expect(actionPreamble).toContain("action.type === 'verify-code'");+ expect(actionPreamble).toContain("action.type === 'start-browser' && action.kind === 'social'");+ expect(actionPreamble).toContain('? AUTH_REGION');+ expect(actionPreamble).toContain('const client = createAuthClient(loginRealm);');++ const personalActionSetup = source.slice(+ source.indexOf('if (!providerConfig) await loadLoginProviders', actionStart),+ source.indexOf("if (action.type === 'discover')", actionStart),+ );+ expect(personalActionSetup).toContain(+ "if (startsBuildRealmFlow && action.type !== 'request-code') pendingAuthRealm = loginRealm;",+ );+ });++ it('keeps cross-region email choices gated and preserves SSO after failed personal code sending', () => {+ const discover = source.slice(+ source.indexOf("if (action.type === 'discover') {"),+ source.indexOf("if (action.type === 'discover-sso-org') {"),+ );+ expect(discover).toContain('discoverEmailLogin(action.email');+ expect(discover.indexOf('discoveredMethods = [];')).toBeLessThan(discover.indexOf('await discoverEmailLogin'));+ expect(discover).toContain('discoverOrganizationRealm(domain, actionLoginFlowEpoch)');+ expect(discover).toContain('pendingAuthRealm = region;');+ expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(discover.indexOf('discoveredMethods = methods;'));+ expect(source).toContain("email: confirmation.email ?? ''");+ const requestStart = source.indexOf("if (action.type === 'request-code') {");+ const request = source.slice(requestStart, source.indexOf("if (action.type === 'verify-code') {", requestStart));+ expect(request.indexOf('pendingAuthRealm = AUTH_REGION;')).toBeGreaterThan(request.indexOf('await client.requestCode('));+ expect(request).toContain('discoveredMethods = [];');+ });++ it('does not leave expired private tickets on a screen that can only reuse them', () => {+ expect(source).toContain("'INVALID_LOGIN_TICKET',");+ expect(source).toContain("'INVALID_BIND_TICKET',");+ expect(source).toContain("'INVALID_SSO_VERIFICATION_TICKET',");+ expect(source).toContain('const errorState = loginPreparingErrorState(');+ expect(source).toContain('? errorState');+ });++ it('keeps account access tokens in memory while persisting only encrypted refresh sessions', () => {+ expect(source).toContain(+ "const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'cindy_auth_account_refresh_token';",+ );+ expect(source).toContain('let pendingAccountToken: string | null = null;');+ expect(source).toContain('client.exchangeAccountMembership(accountToken, action.accountId)');+ expect(source).toContain("const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';");+ expect(source).toContain('client.refreshAccount(current.accountRefreshToken)');+ expect(source).toContain('client.logoutAccount(pair.accountToken)');+ expect(source).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY');+ expect(source).not.toContain('writeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY');+ expect(source).not.toContain('accountToken: accountAccessToken');++ const completeStart = source.indexOf('async function completeLogin(');+ const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ expect(source.slice(completeStart, completeEnd)).toContain('pendingAccountToken = null;');++ const logoutStart = source.indexOf('export async function logout()');+ const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);+ const logoutBody = source.slice(logoutStart, logoutEnd);+ expect(logoutBody).toContain('accessToken: currentAccessToken');+ expect(logoutBody).not.toContain('pendingAccountToken');++ const revokeStart = source.indexOf('function revokeLoggedOutAccountBestEffort(');+ const revokeEnd = source.indexOf('\n}\n\nexport async function logout()', revokeStart);+ expect(source.slice(revokeStart, revokeEnd)).toContain('token: input.accessToken');++ const getterStart = source.indexOf('export function getAccessToken(): string | null {');+ const getterEnd = source.indexOf('\n}', getterStart);+ const getterBody = source.slice(getterStart, getterEnd);+ expect(getterBody).toContain('return accessToken;');+ expect(getterBody).not.toContain('accountAccessToken');+ });++ it('keeps saved account metadata fresh after profile edits and Passport sync', () => {+ expect(source).toContain('const AUTH_ACCOUNT_VAULT_VERSION = 2 as const;');+ expect(source).toContain(+ "const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY = 'cindy_auth_account_logout_tombstones_v1';",+ );+ expect(source).toContain('const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION = 1 as const;');+ expect(source).toContain('const logoutAuthEpoch = authStateEpoch;');+ expect(source).toContain("'Logout was superseded by a newer auth action'");+ expect(source).toContain('validateBeforeCommit: isLogoutStillCurrent');+ expect(source).toContain('shouldClearOnFailure: isLogoutStillCurrent');+ const writePassportStart = source.indexOf('function writePassportSessionToVault(');+ const writePassportEnd = source.indexOf(+ '\n}\n\n/** Persist a rotated Passport',+ writePassportStart,+ );+ const writePassportBody = source.slice(writePassportStart, writePassportEnd);+ expect(writePassportBody).toContain('reconcileSavedAccountMetadata(vault');+ expect(writePassportBody).toContain("passportMode: 'replace-passport'");+ expect(writePassportBody).toContain('loggedOutKeys.has(accountVaultKey(input.realm');++ const readStart = source.indexOf('function readAuthAccountVault(');+ const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);+ const readBody = source.slice(readStart, readEnd);+ expect(readBody).toContain('persistedVersion !== 1');+ expect(readBody).toContain('version: AUTH_ACCOUNT_VAULT_VERSION');++ const writeStart = source.indexOf('function writeAuthAccountVault(');+ const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('JSON.stringify({ ...vault, version: 1 })');+ expect(writeBody).toContain('older client can');+ expect(writeBody).toContain('writeAuthAccountLogoutTombstones(vault)');+ expect(writeBody.indexOf('writeAuthAccountLogoutTombstones(vault)')).toBeLessThan(+ writeBody.indexOf('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY'),+ );++ const logoutTombstoneReadStart = source.indexOf('function readAuthAccountLogoutTombstones(');+ const logoutTombstoneReadEnd = source.indexOf(+ '\n}\n\nfunction writeAuthAccountLogoutTombstones',+ logoutTombstoneReadStart,+ );+ const logoutTombstoneReadBody = source.slice(logoutTombstoneReadStart, logoutTombstoneReadEnd);+ expect(logoutTombstoneReadBody).toContain('parseDesktopAccountKey(key)');+ expect(logoutTombstoneReadBody).toContain('isAtomicPersistedSecretAbsent');+ expect(logoutTombstoneReadBody).toContain('if (options.recoverInvalid) return [];');++ const logoutTombstoneWriteStart = source.indexOf('function writeAuthAccountLogoutTombstones(');+ const logoutTombstoneWriteEnd = source.indexOf(+ '\n}\n\nfunction accountVaultKey',+ logoutTombstoneWriteStart,+ );+ expect(source.slice(logoutTombstoneWriteStart, logoutTombstoneWriteEnd)).toContain(+ 'JSON.stringify({ version: AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION, accountKeys })',+ );++ const readLogoutKeysStart = readBody.indexOf('persistedLogoutKeys =');+ expect(readLogoutKeysStart).toBeGreaterThan(-1);+ expect(readBody).toContain('recoverInvalid: options.recoverInvalid');+ expect(readBody).toContain('if (options.allowUnreadable) return emptyAuthAccountVault();');+ expect(readBody).toContain('new Set([...persistedLogoutKeys, ...embeddedLogoutKeys])');+ expect(readBody).not.toContain('loggedOutKeys.delete(active)');+ expect(readBody).toContain(+ 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',+ );++ const profileStart = source.indexOf('export async function updateServerProfile(');+ const profileEnd = source.indexOf('\n}\n\nexport async function initialize(', profileStart);+ const profileBody = source.slice(profileStart, profileEnd);+ expect(profileBody).toContain('rememberUpdatedMembershipMetadata(');+ expect(profileBody).toContain('membership.passportId ?? currentUser.passportId');+ });++ it('serializes saved-account vault mutations across shared-userData processes', () => {+ const mutationStart = source.indexOf('async function transactAuthAccountVault');+ const mutationEnd = source.indexOf(+ '\n}\n\nasync function mutateAuthAccountVault',+ mutationStart,+ );+ const mutationBody = source.slice(mutationStart, mutationEnd);+ expect(mutationBody).toContain('withCrossProcessLock(');+ expect(mutationBody).toContain(+ "status.reason === 'busy' && options.waitWhileBusyAfterRotation",+ );+ expect(mutationBody).toContain('throw accountVaultLockError(status.reason);');+ expect(mutationBody).toContain("if (attempt.kind === 'committed') return attempt.result;");+ expect(mutationBody.indexOf('const vault = readAuthAccountVault({')).toBeGreaterThan(+ mutationBody.indexOf('if (!status.held)'),+ );+ const vaultWriteAt = mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault');+ expect(vaultWriteAt).toBeGreaterThan(mutationBody.indexOf('await operation(vault);'));+ expect(mutationBody.indexOf('await afterPersist(result);')).toBeGreaterThan(vaultWriteAt);+ expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);');+ expect(mutationBody).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)');+ expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);');+ expect(mutationBody).toContain(+ 'writeAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutRaw)',+ );+ expect(mutationBody).toContain('readAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)');+ expect(mutationBody).toContain('replaceUnreadableLogoutTombstones:');+ expect(mutationBody).toContain('options.replaceUnreadableLogoutTombstones');+ expect(mutationBody).toContain(+ 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',+ );++ for (const helper of [+ 'async function rememberResourceSession(',+ 'async function replaceResourceSessionIfCurrent(',+ 'async function removeRejectedResourceSession(',+ 'async function rememberPassportSession(',+ 'async function replacePassportSessionIfCurrent(',+ 'async function removePassportSessionIfCurrent(',+ 'async function rememberUpdatedMembershipMetadata(',+ 'async function removeVaultAccount(',+ ]) {+ const start = source.indexOf(helper);+ const end = source.indexOf('\n}\n', start);+ expect(start).toBeGreaterThan(-1);+ expect(source.slice(start, end)).toContain('mutateAuthAccountVault(');+ }+ });++ it('filters invalid vault children only for read-only projection', () => {+ const readStart = source.indexOf('function readAuthAccountVault(');+ const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);+ const readBody = source.slice(readStart, readEnd);++ expect(readBody).toContain('if (options.allowUnreadable || options.recoverInvalid) continue;');+ expect(readBody).toContain("throw new Error('invalid saved resource credential')");+ expect(readBody).toContain("throw new Error('invalid saved Passport credential')");+ expect(readBody).toContain("throw new Error('invalid saved Passport membership')");+ expect(readBody).toContain("throw new Error('invalid logged-out account key')");+ expect(readBody).toContain('memberships.length !== item.memberships.length');+ expect(readBody).toContain('allowUnreadableLogoutTombstones?: boolean');+ expect(readBody).toContain('if (options.allowUnreadableLogoutTombstones) {');+ expect(readBody).toContain(+ 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',+ );+ });++ it('recovers invalid Desktop vault content only for a completed explicit login', () => {+ const readStart = source.indexOf('function readAuthAccountVault(');+ const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);+ const readBody = source.slice(readStart, readEnd);+ const unreadableBranch = readBody.slice(+ readBody.indexOf('if (raw === null)'),+ readBody.indexOf('try {'),+ );+ expect(unreadableBranch).not.toContain('recoverInvalid');+ expect(readBody).toContain('options.allowUnreadable || options.recoverInvalid');++ const transactionStart = source.indexOf('async function transactAuthAccountVault');+ const transactionEnd = source.indexOf(+ '\n}\n\nasync function mutateAuthAccountVault',+ transactionStart,+ );+ const transactionBody = source.slice(transactionStart, transactionEnd);+ expect(transactionBody).toContain('recoverInvalidForExplicitLogin?: boolean');+ expect(transactionBody).toContain('recoverInvalid: options.recoverInvalidForExplicitLogin');++ const loginStart = source.indexOf('async function commitDesktopLoginSessions(');+ const loginEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', loginStart);+ const loginBody = source.slice(loginStart, loginEnd);+ expect(loginBody).toContain('recoverInvalidForExplicitLogin: true');+ expect(loginBody).toContain('waitWhileBusyAfterRotation: true');+ const transitionCommit = loginBody.indexOf('await transition.commit();');+ const transitionRollback = loginBody.indexOf('await transition.rollback();');+ expect(transitionCommit).toBeGreaterThan(loginBody.indexOf('await transactAuthAccountVault('));+ expect(transitionRollback).toBeGreaterThan(transitionCommit);+ expect(transitionRollback).toBeLessThan(+ loginBody.indexOf('recoverInvalidForExplicitLogin: true'),+ );+ });++ it('replaces unreadable logout tombstones only for explicit login or logout', () => {+ const writeStart = source.indexOf('function writeAuthAccountVault(');+ const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('replaceUnreadableLogoutTombstones?: boolean');+ expect(writeBody).toContain('const previousLogoutUnreadable =');+ expect(writeBody).toContain('previousLogoutCiphertext === null');+ expect(writeBody).toContain('!options.replaceUnreadableLogoutTombstones');+ expect(writeBody).toContain(+ 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',+ );++ const clearStart = source.indexOf('async function clearAuthAccountVault(');+ const clearEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', clearStart);+ expect(source.slice(clearStart, clearEnd)).toContain(+ 'writeAuthAccountVaultOrThrow(vault, { replaceUnreadableLogoutTombstones: true });',+ );+ });++ it('atomically replaces the aggregate saved-account vault', () => {+ const writeStart = source.indexOf('function writeAtomicSafe(');+ const writeEnd = source.indexOf('\n}\n\nfunction removeAtomicSafeOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('atomicWriteFileSync(');+ expect(writeBody).toContain("safeStorage.encryptString(value).toString('base64')");++ const readStart = source.indexOf('function readAtomicSafe(');+ const readEnd = source.indexOf('\n}\n\nfunction isAtomicPersistedSecretAbsent', readStart);+ expect(source.slice(readStart, readEnd)).toContain('fs.readFileSync(`${filepath}.bak`');++ const clearStart = source.indexOf('function removeAtomicSafeOrThrow(');+ const clearEnd = source.indexOf('\n}\n\nfunction removeSafe(', clearStart);+ const clearBody = source.slice(clearStart, clearEnd);+ expect(clearBody.indexOf('`${filepath}.bak`')).toBeLessThan(clearBody.indexOf('filepath])'));+ });++ it('waits through a busy vault lock after the server has rotated a credential', () => {+ const rotatedCredentialHelpers = [+ ['async function rememberResourceSession(', '\n}\n\ntype ResourceSessionReplacementResult'],+ [+ 'async function replaceResourceSessionIfCurrent(',+ '\n}\n\ntype RejectedResourceSessionRemovalResult',+ ],+ ['async function replacePassportSessionIfCurrent(', '\n}\n\n/** Delete a rejected Passport'],+ ['async function commitDesktopRefreshCredentials(', '\n}\n\n/**\n * Account refresh tokens'],+ ] as const;++ for (const [startMarker, endMarker] of rotatedCredentialHelpers) {+ const start = source.indexOf(startMarker);+ const end = source.indexOf(endMarker, start);+ expect(start).toBeGreaterThan(-1);+ expect(source.slice(start, end)).toContain('waitWhileBusyAfterRotation: true');+ }+ });++ it('fails a Desktop account switch before owner teardown and rolls back under the vault lock', () => {+ const completeStart = source.indexOf('async function completeLogin(');+ const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ const completeBody = source.slice(completeStart, completeEnd);+ const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');+ const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');+ const ownerCommit = completeBody.indexOf('await withCloudOwnerCommit({');+ expect(vaultTransaction).toBeGreaterThan(-1);+ expect(durableSession).toBeGreaterThan(vaultTransaction);+ expect(durableSession).toBeGreaterThan(-1);+ expect(ownerCommit).toBeGreaterThan(durableSession);+ expect(completeBody.indexOf('restorePersistedAuthSessionIfCurrent(')).toBeGreaterThan(+ ownerCommit,+ );+ expect(completeBody.indexOf('rollback: () => {')).toBeGreaterThan(ownerCommit);+ expect(completeBody.slice(ownerCommit)).not.toContain(+ 'writePersistedAuthSession(outcome.refreshToken',+ );+ });++ it('invalidates pending add-account actions without cancelling an accepted login commit', () => {+ const runStart = source.indexOf('async function runLoginAction(');+ expect(runStart).toBeGreaterThan(-1);+ const runEnd = source.indexOf('\n}\n\nexport async function dispatchLoginAction', runStart);+ const runBody = source.slice(runStart, runEnd);+ expect(runBody).toContain('const actionLoginFlowEpoch = loginFlowEpoch;');+ expect(runBody).toContain('assertLoginFlowCurrent(actionLoginFlowEpoch);');+ expect(runBody).toContain("code: 'AUTH_FLOW_SUPERSEDED'");++ const completeStart = source.indexOf('async function completeLogin(');+ const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ const completeBody = source.slice(completeStart, completeEnd);+ expect(completeBody).toContain('expectedLoginFlowEpoch = loginFlowEpoch');+ expect(completeBody).toContain('loginFlowEpoch !== expectedLoginFlowEpoch');+ expect(completeBody).toContain(+ 'const releaseLoginFlowCommit = sealLoginFlowCommit(expectedLoginFlowEpoch);',+ );+ expect(completeBody).toContain('releaseLoginFlowCommit();');+ const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');+ const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');+ const teardown = completeBody.indexOf('await accountSwitchTeardown(');+ expect(vaultTransaction).toBeGreaterThan(-1);+ expect(durableSession).toBeGreaterThan(vaultTransaction);+ expect(completeBody.lastIndexOf('assertTransitionCurrent();', teardown)).toBeLessThan(teardown);+ expect(completeBody).toContain('restorePersistedAuthSessionIfCurrent(');++ const cancelStart = source.indexOf('export function cancelAddAccountLogin(): void {');+ const cancelEnd = source.indexOf('\n}\n\nexport function getCurrentDataOwnerId', cancelStart);+ const cancelBody = source.slice(cancelStart, cancelEnd);+ expect(cancelBody).toContain('if (isLoginFlowCommitSealed(loginFlowEpoch))');+ expect(cancelBody).toContain('loginFlowEpoch += 1;');+ expect(cancelBody.indexOf('isLoginFlowCommitSealed')).toBeLessThan(+ cancelBody.indexOf('loginFlowEpoch += 1;'),+ );+ });++ it('single-flights Passport refresh and rejects cross-realm personal account switching', () => {+ const helperStart = source.indexOf('async function refreshPassportSessionSingleFlight(');+ const helperEnd = source.indexOf(+ '\n}\n\nasync function rememberUpdatedMembershipMetadata',+ helperStart,+ );+ const helperBody = source.slice(helperStart, helperEnd);+ expect(helperBody).toContain('passportAccountRefreshFlights.get(key)');+ expect(helperBody).toContain('replacePassportSessionIfCurrent({');+ expect(helperBody).toContain('removePassportSessionIfCurrent(');+ expect(helperBody.indexOf("error.code === 'DEVICE_MISMATCH'")).toBeLessThan(+ helperBody.indexOf('removePassportSessionIfCurrent('),+ );+ expect(source).toContain("'write-failed'");+ expect(source).toContain("'CREDENTIAL_STORE_UNAVAILABLE'");+ expect(source).toContain('isPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)');+ expect(source).toContain('readAuthAccountVault({ allowUnreadable: true })');+ expect(source).toContain('writeAuthAccountVaultOrThrow(vault');++ const syncStart = source.indexOf('export async function syncSavedAccounts()');+ const syncEnd = source.indexOf('\n}\n\nexport async function switchSavedAccount', syncStart);+ const syncBody = source.slice(syncStart, syncEnd);+ expect(syncBody).toContain('refreshPassportSessionSingleFlight(');++ const switchStart = syncEnd;+ const switchEnd = source.indexOf(+ '\n}\n\nexport async function beginAddAccountLogin',+ switchStart,+ );+ const switchBody = source.slice(switchStart, switchEnd);+ const policyGuard = switchBody.indexOf('!canRestoreAuthSessionForMembership(');+ const commitRealm = switchBody.indexOf('pendingAuthRealm = realm;');+ expect(policyGuard).toBeGreaterThan(-1);+ expect(commitRealm).toBeGreaterThan(policyGuard);+ expect(switchBody).toContain('refreshPassportSessionSingleFlight(');+ expect(switchBody).toContain('refreshSavedResourceSession({');+ expect(switchBody).not.toContain('client.refresh(resource.refreshToken)');+ expect(switchBody).not.toContain('removeVaultAccount(parsedKey)');+ expect(switchBody).toContain("'REGION_MISMATCH'");+ expect(switchBody).toContain('const switchLoginFlowEpoch = loginFlowEpoch;');+ expect(switchBody).toContain(+ "await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch, {",+ );+ expect(switchBody).toContain('restoreLoggedOutAccount: false');+ expect(switchBody).toContain('accountToLogOut: options.accountToLogOut');+ expect(switchBody).toContain('validateBeforeCommit: options.validateBeforeCommit');++ const completeLoginStart = source.indexOf('async function completeLogin(');+ const completeLoginEnd = source.indexOf(+ '\n}\n\nasync function runLoginAction',+ completeLoginStart,+ );+ const completeLoginBody = source.slice(completeLoginStart, completeLoginEnd);+ expect(completeLoginBody).toContain('validateBeforeCommit?: (loginEpoch: number) => void;');+ expect(completeLoginBody).toContain('options.validateBeforeCommit?.(loginEpoch);');++ const resourceRefreshStart = source.indexOf('async function refreshSavedResourceSession(');+ const resourceRefreshEnd = source.indexOf(+ '\n}\n\nfunction readPersistedAuthSession()',+ resourceRefreshStart,+ );+ const resourceRefreshBody = source.slice(resourceRefreshStart, resourceRefreshEnd);+ expect(resourceRefreshBody).toContain('runRefreshWithReplacementRetry<RefreshAttemptData>(');+ expect(resourceRefreshBody).toContain(+ 'readAuthAccountVault().resources[input.accountKey]?.refreshToken',+ );+ expect(resourceRefreshBody).toContain('replaceResourceSessionIfCurrent({');+ expect(resourceRefreshBody).toContain('removeRejectedResourceSession({');+ expect(resourceRefreshBody).toContain("if (removal === 'stale')");+ expect(resourceRefreshBody).toContain("'AUTH_FLOW_SUPERSEDED'");+ expect(resourceRefreshBody).toContain("lastRefreshError.code === 'DEVICE_MISMATCH'");+ });++ it('keeps account refresh out of resource-token cold-start initialization', () => {+ const initializeStart = source.indexOf('export async function initialize(');+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);+ const initializeBody = source.slice(initializeStart, initializeEnd);+ const authenticatedFastPath = initializeBody.indexOf('if (accessToken && currentUser)');++ expect(authenticatedFastPath).toBeGreaterThan(-1);+ expect(initializeBody).toContain('removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);');+ expect(initializeBody).not.toContain('refreshAccount');+ expect(initializeBody).not.toContain('restoreAccountSelection');+ });++ it('returns a committed local session before reading or refreshing cloud credentials', () => {+ const initializeStart = source.indexOf('export async function initialize(');+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);+ const initializeBody = source.slice(initializeStart, initializeEnd);+ const localGuard = initializeBody.indexOf("getActiveAppSession().mode === 'local'");+ const refreshTokenRead = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');++ expect(localGuard).toBeGreaterThan(-1);+ expect(refreshTokenRead).toBeGreaterThan(localGuard);+ expect(initializeBody.slice(localGuard, refreshTokenRead)).toContain(+ 'return snapshotAuthState();',+ );+ });++ it('preserves compatibility and vault generations before cold-start refresh', () => {+ const helperStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');+ const helperEnd = source.indexOf('\n}\n\nfunction readPersistedRefreshToken', helperStart);+ const helperBody = source.slice(helperStart, helperEnd);+ expect(helperBody).toContain('authAccountVaultLockPath()');+ expect(helperBody).toContain("label: 'auth-account-vault-reconcile'");+ expect(helperBody).toContain('vault.resources[vault.activeAccountKey]');+ expect(helperBody).toContain('if (!session)');+ expect(helperBody).toContain('writePersistedAuthSessionOrThrow(');+ expect(helperBody).toContain('return session;');++ const candidatesStart = source.indexOf('function readStoredRefreshTokenCandidates');+ const candidatesEnd = source.indexOf(+ '\n}\n\nfunction readPersistedAccountDeletionReceipt',+ candidatesStart,+ );+ const candidatesBody = source.slice(candidatesStart, candidatesEnd);+ expect(candidatesBody).toContain('readPersistedRefreshToken(realm)');+ expect(candidatesBody).toContain('vault.resources[vault.activeAccountKey]');+ expect(candidatesBody).toContain('activeResource.refreshToken');++ const commitStart = source.indexOf('async function commitDesktopRefreshCredentials');+ const commitEnd = source.indexOf(+ '\n}\n\n/**\n * Account refresh tokens have no replay grace.',+ commitStart,+ );+ const commitBody = source.slice(commitStart, commitEnd);+ expect(commitBody).toContain('vault.resources[key]?.refreshToken === requestedRefreshToken');++ const deadStart = source.indexOf('async function clearConfirmedDeadRefreshTokens');+ const deadEnd = source.indexOf('\n}\n\n/**\n * replacement-retry', deadStart);+ const deadBody = source.slice(deadStart, deadEnd);+ expect(deadBody).toContain('await mutateAuthAccountVault((vault) => {');+ expect(deadBody).toContain('deadTokens.includes(activeResource.refreshToken)');+ expect(deadBody).toContain('delete vault.resources[activeKey];');+ expect(deadBody).toContain('vault.activeAccountKey = null;');++ const listStart = source.indexOf('export function listSavedAccounts()');+ const listEnd = source.indexOf('\n}\n\nexport async function syncSavedAccounts', listStart);+ const listBody = source.slice(listStart, listEnd);+ expect(listBody).toContain(+ 'const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;',+ );++ const initializeStart = source.indexOf('export async function initialize(');+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);+ const initializeBody = source.slice(initializeStart, initializeEnd);+ const reconcileAt = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');+ const refreshAt = initializeBody.indexOf(+ 'runColdStartRefreshFlow(storedToken, persistedSession.realm)',+ );+ expect(reconcileAt).toBeGreaterThan(-1);+ expect(refreshAt).toBeGreaterThan(reconcileAt);+ });++ it('keeps a durable signed-out owner across a crash between vault and session cleanup', () => {+ expect(source).toContain('signedOutAt?: number;');++ const clearStart = source.indexOf('async function clearAuthAccountVault(');+ const clearEnd = source.indexOf('\n}\n\nfunction persistLogoutTombstoneOnly', clearStart);+ const clearBody = source.slice(clearStart, clearEnd);+ expect(clearBody).toContain('withCrossProcessLock(');+ expect(clearBody).toContain("label: 'auth-account-vault-clear'");+ expect(clearBody).toContain('const vault = emptyAuthAccountVault();');+ expect(clearBody).toContain('vault.activeAccountKey = null;');+ expect(clearBody).toContain('vault.resources = {};');+ expect(clearBody).toContain('vault.passports = {};');+ expect(clearBody).toContain('vault.signedOutAt = Date.now();');+ expect(clearBody.indexOf('writeAuthAccountVaultOrThrow(vault);')).toBeLessThan(+ clearBody.indexOf('await afterPersist();'),+ );++ const tombstoneStart = source.indexOf('async function persistLogoutTombstoneOnly(');+ const tombstoneEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', tombstoneStart);+ const tombstoneBody = source.slice(tombstoneStart, tombstoneEnd);+ expect(tombstoneBody).toContain("label: 'auth-account-logout-tombstone'");+ expect(tombstoneBody).toContain('readAuthAccountLogoutTombstones({ recoverInvalid: true })');+ expect(tombstoneBody).toContain('writeAuthAccountLogoutTombstones(vault)');+ expect(tombstoneBody).not.toContain('writeAuthAccountVaultOrThrow');++ const reconcileStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');+ const reconcileEnd = source.indexOf(+ '\n}\n\nfunction readPersistedRefreshToken',+ reconcileStart,+ );+ const reconcileBody = source.slice(reconcileStart, reconcileEnd);+ const tombstoneGuard = reconcileBody.indexOf("typeof vault.signedOutAt === 'number'");+ expect(tombstoneGuard).toBeGreaterThan(-1);+ expect(reconcileBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneGuard);+ expect(reconcileBody.indexOf('return null;')).toBeGreaterThan(tombstoneGuard);+ expect(reconcileBody.indexOf('writePersistedAuthSessionOrThrow(')).toBeGreaterThan(+ tombstoneGuard,+ );++ const refreshCommitStart = source.indexOf('async function commitDesktopRefreshCredentials(');+ const refreshCommitEnd = source.indexOf(+ '\n}\n\n/**\n * Account refresh tokens',+ refreshCommitStart,+ );+ const refreshCommitBody = source.slice(refreshCommitStart, refreshCommitEnd);+ expect(refreshCommitBody).toContain("typeof vault.signedOutAt !== 'number'");+ expect(refreshCommitBody).toContain('!loggedOutAccountKeySet(vault).has(key)');+ expect(refreshCommitBody.indexOf('!loggedOutAccountKeySet(vault).has(key)')).toBeGreaterThan(+ refreshCommitBody.indexOf('options.allowUnclaimedVault === true'),+ );++ const resourceWriteStart = source.indexOf('function writeResourceSessionToVault(');+ const resourceWriteEnd = source.indexOf(+ '\n}\n\nasync function rememberPassportSession',+ resourceWriteStart,+ );+ const resourceWriteBody = source.slice(resourceWriteStart, resourceWriteEnd);+ expect(resourceWriteBody).toContain('if (options.markActive !== false) {');+ expect(resourceWriteBody).toContain('delete vault.signedOutAt;');+ expect(resourceWriteBody).toContain(+ 'if (options.restoreLoggedOutAccount) restoreLoggedOutVaultAccount(vault, key);',+ );++ const loginCommitStart = source.indexOf('async function commitDesktopLoginSessions(');+ const loginCommitEnd = source.indexOf(+ '\n}\n\n/** Persist a rotated Passport',+ loginCommitStart,+ );+ const loginCommitBody = source.slice(loginCommitStart, loginCommitEnd);+ expect(loginCommitBody).toContain('if (!input.passportId) {');+ expect(loginCommitBody).toContain('delete vault.signedOutAt;');+ expect(loginCommitBody).toContain('removeLoggedOutVaultAccount(vault, input.accountToLogOut)');++ const logoutStart = source.indexOf('export async function logout(): Promise<void> {');+ const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);+ const logoutBody = source.slice(logoutStart, logoutEnd);+ const tombstoneCommit = logoutBody.indexOf('await mutateAuthAccountVault(');+ const ownerTeardown = logoutBody.indexOf('await withAccountFreeOwnerCommit({');+ expect(tombstoneCommit).toBeGreaterThan(-1);+ expect(logoutBody).toContain('savedVaultWasUnreadable');+ expect(logoutBody).toContain('await persistLogoutTombstoneOnly(currentIdentity.accountKey);');+ expect(logoutBody).not.toContain('clearAuthAccountVault((vault) => {');+ expect(logoutBody).toContain('savedVaultHasUnreadableLogoutTombstones');+ expect(logoutBody).toContain(+ 'const candidateAccountKeys = savedVaultHasUnreadableLogoutTombstones',+ );+ expect(logoutBody).toContain(+ 'replaceUnreadableLogoutTombstones: savedVaultHasUnreadableLogoutTombstones',+ );+ expect(logoutBody).toContain('removeLoggedOutVaultAccount(vault, currentIdentity)');+ expect(logoutBody).toContain('vault.signedOutAt = Date.now();');+ expect(logoutBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneCommit);+ expect(ownerTeardown).toBeGreaterThan(tombstoneCommit);+ expect(logoutBody).toContain('preservePersistedRefreshToken: true');+ });++ it('logs out only the current saved account and advances to the next restorable account', () => {+ expect(source).toContain('loggedOutAccountKeys?: string[];');++ const removalStart = logoutPolicySource.indexOf('export function removeLoggedOutVaultAccount<');+ const removalBody = logoutPolicySource.slice(removalStart);+ expect(removalBody).toContain('delete vault.resources[identity.accountKey];');+ expect(removalBody).toContain('loggedOutKeys.add(identity.accountKey);');+ expect(removalBody).toContain('const hasRestorableSibling =');+ expect(removalBody).toContain('if (hasRestorableSibling) return null;');+ expect(removalBody).toContain('delete vault.passports[passportKey];');++ const summariesStart = source.indexOf('function savedAccountSummaries(');+ const summariesEnd = source.indexOf('\n}\n\nexport function listSavedAccounts', summariesStart);+ const summariesBody = source.slice(summariesStart, summariesEnd);+ expect(summariesBody).toContain('const loggedOutKeys = loggedOutAccountKeySet(vault);');+ expect(summariesBody).toContain(+ 'if (!loggedOutKeys.has(key)) byKey.set(key, resource.metadata);',+ );+ expect(summariesBody).toContain('return rightUsed - leftUsed');++ const logoutStart = source.indexOf('export async function logout(): Promise<void> {');+ const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);+ const logoutBody = source.slice(logoutStart, logoutEnd);+ const candidateLoop = logoutBody.indexOf(+ 'for (const candidateAccountKey of candidateAccountKeys)',+ );+ const terminalSignOut = logoutBody.indexOf('await mutateAuthAccountVault(');+ expect(candidateLoop).toBeGreaterThan(-1);+ expect(logoutBody).toContain('await switchSavedAccount(candidateAccountKey, {');+ expect(logoutBody).toContain('accountToLogOut: currentIdentity');+ expect(logoutBody).toContain('validateBeforeCommit: (loginEpoch) => {');+ expect(logoutBody).toContain('assertLogoutStillCurrent(loginEpoch);');+ expect(logoutBody).toContain('candidateTransitionEpoch = loginEpoch;');+ expect(logoutBody).toContain('assertLogoutTransitionStillCurrent(candidateTransitionEpoch);');+ expect(logoutBody).toContain('assertLogoutStillCurrent();');+ expect(logoutBody).toContain('if (isUnavailableSavedAccountError(error)) continue;');+ expect(logoutBody).toContain('isRetryableSavedAccountSwitchError(error)');+ const retryableSwitchStart = source.indexOf('function isRetryableSavedAccountSwitchError(');+ const retryableSwitchEnd = source.indexOf(+ '\n}\n\nfunction revokeLoggedOutAccountBestEffort',+ retryableSwitchStart,+ );+ const retryableSwitchBody = source.slice(retryableSwitchStart, retryableSwitchEnd);+ expect(retryableSwitchBody).toContain('error.statusCode === 429');+ expect(retryableSwitchBody).toContain("'RATE_LIMITED'");+ expect(logoutBody.indexOf('return;', candidateLoop)).toBeLessThan(terminalSignOut);+ expect(terminalSignOut).toBeGreaterThan(candidateLoop);+ expect(logoutBody).not.toContain('revokeSavedSessionsBestEffort');+ });++ it('activates a restored realm only after the refreshed membership passes build policy', () => {+ const initializeStart = source.indexOf('export async function initialize(');+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);+ const initializeBody = source.slice(initializeStart, initializeEnd);+ expect(initializeBody).toContain('await loadClientEndpointsForRealm(persistedSession.realm);');+ expect(initializeBody).not.toContain('activateClientEndpointRealm(persistedSession.realm);');++ const coldStart = source.indexOf('async function runColdStartRefreshFlow(');+ const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);+ const coldBody = source.slice(coldStart, coldEnd);+ const coldCredentialCommit = coldBody.indexOf('await commitDesktopRefreshCredentials(');+ const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');+ const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');+ expect(coldCredentialCommit).toBeGreaterThan(-1);+ expect(coldPolicyGuard).toBeGreaterThan(-1);+ expect(coldCredentialCommit).toBeLessThan(coldPolicyGuard);+ expect(coldRealmActivation).toBeGreaterThan(coldPolicyGuard);+ expect(coldBody).toContain('requestedToken,');+ expect(coldBody).toContain('allowUnclaimedVault: true');+ expect(coldBody).toContain("epochChanged('before-cold-start-credential-commit')");+ expect(coldBody).toContain("credentialCommit !== 'active'");+ const inactiveCommit = coldBody.indexOf("credentialCommit !== 'active'");+ const activeCandidateRead = coldBody.indexOf(+ 'readActiveVaultRefreshCandidate()',+ inactiveCommit,+ );+ const ownershipRetry = coldBody.indexOf('return runColdStartRefreshFlow(', activeCandidateRead);+ expect(activeCandidateRead).toBeGreaterThan(inactiveCommit);+ expect(ownershipRetry).toBeGreaterThan(activeCandidateRead);+ expect(coldBody.slice(inactiveCommit, ownershipRetry)).toContain(+ '!attemptedOwnershipTokens.has(nextActiveCandidate.refreshToken)',+ );+ expect(coldBody).not.toContain(+ 'writePersistedAuthSession(refreshData.refreshToken, storedRealm)',+ );+ expect(coldBody).not.toContain('rememberResourceSession(refreshData');++ const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');+ const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);+ const refreshBody = source.slice(refreshStart, refreshEnd);+ const runtimePolicyGuard = refreshBody.indexOf('!canRestoreAuthSessionForMembership(');+ const runtimeRealmActivation = refreshBody.indexOf(+ 'activateClientEndpointRealm(refreshRealm);',+ );+ expect(runtimePolicyGuard).toBeGreaterThan(-1);+ expect(runtimeRealmActivation).toBeGreaterThan(runtimePolicyGuard);+ expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');+ expect(refreshBody).toContain(+ "await expireRuntimeAuth(currentUser.id, 'replaced-elsewhere', {",+ );+ expect(refreshBody).toContain('preservePersistedRefreshToken: true');+ });++ it('retries the vault active account after a stale compatibility token fails on cold start', () => {+ const coldStart = source.indexOf('async function runColdStartRefreshFlow(');+ const coldStartEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', coldStart);+ const coldStartBody = source.slice(coldStart, coldStartEnd);+ expect(coldStartBody).toContain(+ 'const nextActiveCandidate = readActiveVaultRefreshCandidate();',+ );+ expect(coldStartBody).toContain(+ 'cold-start refresh rejected a stale compatibility token; continuing with the vault active account',+ );+ expect(coldStartBody).toContain(+ 'expectedActiveVaultAccountKey: nextActiveCandidate.accountKey',+ );+ const clearDeadTokens = coldStartBody.indexOf('await clearConfirmedDeadRefreshTokens(');+ const staleEpochGuard = coldStartBody.indexOf(+ "epochChanged('after-clearing-confirmed-dead-tokens')",+ clearDeadTokens,+ );+ const ownershipRetry = coldStartBody.indexOf(+ 'return runColdStartRefreshFlow(',+ clearDeadTokens,+ );+ expect(clearDeadTokens).toBeGreaterThan(-1);+ expect(staleEpochGuard).toBeGreaterThan(clearDeadTokens);+ expect(ownershipRetry).toBeGreaterThan(staleEpochGuard);+ });++ it('unlocks login preparing with the splash startup gate after 30s', () => {+ const loadStart = source.indexOf('async function loadLoginProviders(');+ const loadEnd = source.indexOf('\n}\n\nasync function discoverOrganizationRealm(', loadStart);+ const loadBody = source.slice(loadStart, loadEnd);+ expect(loadBody).toContain('await awaitLoginProvidersWithPreparingGate(');+ expect(loadBody).toContain('createAuthClient(AUTH_REGION).getProviders()');+ // 闸只限时等待,不 abort 在途 getProviders(与 splash 冷启动闸同一语义)。+ expect(loadBody).not.toContain('.abort(');++ const getLoginStart = source.indexOf('export async function getLoginState(');+ const getLoginEnd = source.indexOf('\n}\n\nasync function completeLogin(', getLoginStart);+ const getLoginBody = source.slice(getLoginStart, getLoginEnd);+ const waitForOwnerChange = getLoginBody.indexOf('await ownerChangeShellGate.waitForSettled();');+ const captureLoginEpoch = getLoginBody.indexOf(+ 'const expectedLoginFlowEpoch = loginFlowEpoch;',+ );+ expect(waitForOwnerChange).toBeGreaterThan(-1);+ expect(captureLoginEpoch).toBeGreaterThan(-1);+ expect(waitForOwnerChange).toBeLessThan(captureLoginEpoch);+ expect(getLoginBody).toContain('await loadLoginProviders(expectedLoginFlowEpoch)');+ expect(getLoginBody).toContain('mapLoginProvidersLoadFailure(error)');+ });++ it('drops a runtime refresh result after logout or a newer login changes auth generation', () => {+ const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');+ const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);+ const refreshBody = source.slice(refreshStart, refreshEnd);+ expect(refreshBody).toContain('const refreshEpoch = authStateEpoch;');+ expect(refreshBody).toContain("refreshWasSuperseded('after-refresh')");+ // 'after-product-me' 守卫点已随产品 /api/user/me 退役(2026-07):refresh+ // 与提交之间不再有产品资料网络往返,该迟到窗口不存在了。+ expect(refreshBody).not.toContain('/api/user/me');+ expect(refreshBody).toContain("refreshWasSuperseded('after-account-switch-teardown')");+ expect(refreshBody).toContain("refreshWasSuperseded('after-integration-reload')");+ expect(refreshBody).toContain("refreshWasSuperseded('catch')");+ expect(refreshBody).toContain('latestSession.refreshToken === requestedToken');+ expect(refreshBody).toContain("credentialCommit !== 'active'");++ const helperStart = source.indexOf('async function commitDesktopRefreshCredentials(');+ const helperEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', helperStart);+ const helperBody = source.slice(helperStart, helperEnd);+ expect(helperBody).toContain('vault.activeAccountKey === key');+ expect(helperBody).toContain('options.validateBeforeWrite?.()');+ expect(helperBody).toContain('canClaimUninitializedVault');+ expect(helperBody).toContain('Object.keys(vault.resources).length === 0');+ expect(helperBody).toContain('readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)');+ expect(helperBody).toContain('markActive: stillOwnsActiveSession');+ expect(helperBody).toContain("if (commit === 'active') {");+ expect(helperBody).toContain('writePersistedAuthSessionOrThrow(pair.refreshToken, realm);');+ });++ it('advances the existing owner generation when login or restoration commits another realm', () => {+ for (const [entry, realm] of [+ ['async function runColdStartRefreshFlow(', 'storedRealm'],+ ['async function completeLogin(', 'committedRealm'],+ ]) {+ const start = source.indexOf(entry);+ expect(start).toBeGreaterThan(-1);+ const body = source.slice(start, source.indexOf('\n}\n', start));+ const capture = body.indexOf(`const authRealmChanged = ${realm} !== activeAuthRealm;`);+ const activate = body.indexOf(`activeAuthRealm = ${realm};`);+ const commit = body.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');+ expect(capture).toBeGreaterThan(-1);+ expect(activate).toBeGreaterThan(capture);+ expect(commit).toBeGreaterThan(activate);+ }+ const start = source.indexOf('function commitCloudAppSession(');+ const helper = source.slice(start, source.indexOf('\n}\n', start));+ expect(helper).toContain("commitActiveAppSession('cloud', ownerId, authRealmChanged);");+ expect(helper).toContain("commitVolatileAppSession('cloud', ownerId, authRealmChanged);");+ });++ it('reconnects realm-bound main clients after a runtime realm change commits its new token', () => {+ const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');+ const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);+ const refreshBody = source.slice(refreshStart, refreshEnd);++ expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');+ expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');+ expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');+ expect(refreshBody.match(/commitCloudAppSession\(currentUser.id, authRealmChanged\);/g)).toHaveLength(2);+ expect(refreshBody).toContain(+ 'const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',+ );+ expect(refreshBody).toContain(+ 'previousUserId !== nextUser.id || authRealmChanged || membershipKindChanged',+ );+ expect(refreshBody).toContain(+ 'if (authRealmChanged || membershipKindChanged) {\n notifyAuthListeners();',+ );++ expect(deviceLinkSource).toContain('restartDeviceLinkForAuthRealmChange();');+ expect(deviceLinkSource).toContain('void stopArbitrationAndTeardown()');+ expect(deviceLinkSource).toContain('authManager.getActiveAuthRealm() !== targetRealm');+ expect(hookControlSource).toContain('} else if (realmChanged) {');+ expect(hookControlSource).toContain('manager?.sync();');+ });++ it('tears down the owner boundary before notifying runtime auth expiry', () => {+ const helperStart = source.indexOf('async function expireRuntimeAuth(');+ const helperEnd = source.indexOf('\n}\n\n// ── Public API', helperStart);+ const helperBody = source.slice(helperStart, helperEnd);+ expect(helperBody).toContain('clearAuth({ notify: false,');+ expect(helperBody).toContain('await withAccountFreeOwnerCommit({');+ expect(helperBody).toContain('authAlreadyCleared: true');+ expect(helperBody).toContain('notifySessionExpired(reason);');++ const ownerCommitStart = source.indexOf('async function withAccountFreeOwnerCommit(');+ const ownerCommitEnd = source.indexOf(+ '\n}\n\nasync function withCloudOwnerCommit(',+ ownerCommitStart,+ );+ const ownerCommitBody = source.slice(ownerCommitStart, ownerCommitEnd);+ expect(ownerCommitBody).toContain('beginAppSessionBoundary()');+ expect(ownerCommitBody).toContain('notifyRendererAuthBoundaryPending();');+ expect(ownerCommitBody).toContain('await accountSwitchTeardown');+ expect(ownerCommitBody).toContain('await authSessionTeardown(opts.reason);');+ expect(ownerCommitBody).toContain('notifyAuthListeners();');++ const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');+ const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);+ const refreshBody = source.slice(refreshStart, refreshEnd);+ expect(refreshBody).toContain(+ 'await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));',+ );+ expect(refreshBody).not.toContain('clearAuth({ notify: false });');+ });++ it('reserves local namespaces before publishing a cloud owner', () => {+ const cloudStart = source.indexOf('async function withCloudOwnerCommit(');+ const prepareStart = source.indexOf('prepareCommit: async () => {', cloudStart);+ const prepareEnd = source.indexOf('\n },\n commit: async () => {', prepareStart);+ const prepareBody = source.slice(prepareStart, prepareEnd);++ expect(prepareBody).toContain(+ 'rollbackReservation = reserveCloudOwnerData(opts.nextOwnerId, opts.previousOwnerId);',+ );+ expect(prepareBody.indexOf('reserveCloudOwnerData')).toBeLessThan(+ prepareBody.indexOf('await opts.prepareCommit?.();'),+ );+ expect(source).toContain('await repairStableCloudOwnerDataReservations(currentUser.id);');+ expect(source).toContain('if (reservation && !reservation.finalize())');+ expect(source).toContain('if (!reservation.rollback())');+ expect(source).toContain('if (boundaryCommitApplied || commitApplied) return;');++ const failureStart = source.indexOf(+ 'onCommitFailure: ({ commitApplied: boundaryCommitApplied }) => {',+ cloudStart,+ );+ const failureEnd = source.indexOf('\n },\n });', failureStart);+ const failureBody = source.slice(failureStart, failureEnd);+ expect(failureBody).toContain('if (boundaryCommitApplied || commitApplied) return;');+ expect(failureBody.indexOf('if (!reservation.rollback())')).toBeLessThan(+ failureBody.indexOf('rollbackReservation = null;'),+ );+ const finallyStart = source.indexOf(' } finally {', failureEnd);+ const finallyBody = source.slice(finallyStart, source.indexOf('\n }\n', finallyStart));+ expect(finallyBody).toContain('if (!committed && !commitApplied)');++ const repairStart = source.indexOf(+ 'function repairStableCloudOwnerDataReservationsWhileLocked(',+ );+ const repairEnd = source.indexOf(+ '\n}\n\nasync function repairStableCloudOwnerDataReservations(',+ repairStart,+ );+ const repairBody = source.slice(repairStart, repairEnd);+ expect(repairBody).toContain('reserveCommittedLocalProfileDataOwnerDetailed(');+ expect(repairBody).toContain(+ 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',+ );+ expect(repairBody).toContain(+ 'reserveCommittedLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',+ );+ expect(repairBody).toContain(+ 'reserveCommittedLegacyNativeProviderAuthOwner(authoritativeOwnerId)',+ );+ expect(repairBody).not.toContain('reserveLocalProfileDataOwnerDetailed(');+ expect(repairBody).not.toContain('reserveLegacyNativeProviderAuthOwnerDetailed(ownerId)');+ expect(repairBody).toContain('remains authenticated with local adoption fail-closed');+ expect(repairBody).not.toContain('throw new Error');+ const serializedRepairStart = source.indexOf(+ 'async function repairStableCloudOwnerDataReservations(',+ );+ const serializedRepairEnd = source.indexOf(+ '\n}\n\nfunction commitCloudAppSession(',+ serializedRepairStart,+ );+ const serializedRepairBody = source.slice(serializedRepairStart, serializedRepairEnd);+ expect(serializedRepairBody).toContain('withStableOwnerBoundaryMutation(ownerId');+ expect(serializedRepairBody).toContain(+ 'repairStableCloudOwnerDataReservationsWhileLocked(ownerId)',+ );++ const reserveStart = source.indexOf('function reserveCloudOwnerData(');+ const reserveEnd = source.indexOf(+ '\n}\n\nfunction repairStableCloudOwnerDataReservationsWhileLocked(',+ reserveStart,+ );+ const reserveBody = source.slice(reserveStart, reserveEnd);+ expect(reserveBody).toContain(+ 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',+ );+ expect(reserveBody).toContain(+ 'reserveLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',+ );+ expect(reserveBody).toContain(+ 'releaseLocalProfileDataOwner(\n profileReservationOwnerId,',+ );+ expect(reserveBody).toContain(+ "if (nativeReservation.status === 'claimed' && nativeReservation.claimToken)",+ );+ expect(reserveBody).not.toContain(+ "profileReservation.status === 'claimed' &&\n nativeReservation.status === 'claimed'",+ );+ expect(reserveBody).toContain('const authoritativeOwnerId = profileReservation.ownerId;');+ expect(reserveBody).toContain(+ 'reserveLegacyNativeProviderAuthOwnerDetailed(authoritativeOwnerId)',+ );+ expect(reserveBody).toContain(+ "throw new Error('local profile and native provider ownership reservations disagree')",+ );+ expect(reserveBody).toContain(+ 'finalize: () => recoverCloudOwnerDataReservations(authoritativeOwnerId)',+ );++ const migrationStart = source.indexOf(+ 'async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Promise<void> {',+ );+ const migrationEnd = source.indexOf(+ '\n}\n\nasync function finishColdStartSignedOut(',+ migrationStart,+ );+ const migrationBody = source.slice(migrationStart, migrationEnd);+ expect(migrationBody).toContain(+ 'if (!(await repairStableCloudOwnerDataReservations(ownerId))) return;',+ );+ expect(migrationBody.indexOf('repairStableCloudOwnerDataReservations')).toBeLessThan(+ migrationBody.indexOf('migrateLocalNativeProviderAuthBindings'),+ );+ });++ it('synchronizes canary flags on every path that establishes a new auth identity', () => {+ expect(source).not.toContain('canaryFlagStore.sync(false)');+ expect(source.match(/scheduleCanaryFlagSync\(\{/g)).toHaveLength(3);+ expect(source.match(/scheduleXdOrgBetaDefault\(\{/g)).toHaveLength(3);+ expect(source.match(/scheduleNonXdOrgBetaDefault\(\{/g)).toHaveLength(1);+ expect(source).toContain("getClientEndpoint('oauthBrokerApiBaseUrl')");+ expect(source).toContain("apiFetch('/api/user/feature-flags'");++ const syncStart = source.indexOf('function scheduleCanaryFlagSync(');+ const syncEnd = source.indexOf(+ '\n}\n\n/**\n * 登录态落地后为 xd 组织补一次设备级 beta 默认值',+ syncStart,+ );+ expect(syncEnd).toBeGreaterThan(syncStart);+ const syncBody = source.slice(syncStart, syncEnd);+ expect(syncBody).toContain("if (outcome.kind === 'synced')");+ expect(syncBody).toContain('notifyRenderer();');++ const completeStart = source.indexOf('async function completeLogin(');+ const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ const completeBody = source.slice(completeStart, completeEnd);+ const acceptedUser = completeBody.indexOf('currentUser = nextUser;');+ const ownerCommit = completeBody.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');+ const clearPreviousFlag = completeBody.indexOf('canaryFlagStore.clear();', acceptedUser);+ expect(acceptedUser).toBeGreaterThan(-1);+ expect(clearPreviousFlag).toBeGreaterThan(acceptedUser);+ expect(ownerCommit).toBeGreaterThan(clearPreviousFlag);+ expect(completeBody.slice(acceptedUser, clearPreviousFlag)).toContain(+ 'if (!isPassiveSharedUserDataInstance()) {',+ );++ const betaStart = source.indexOf('function scheduleXdOrgBetaDefault(');+ const betaEnd = source.indexOf('function scheduleNonXdOrgBetaDefault(', betaStart);+ expect(betaEnd).toBeGreaterThan(betaStart);+ const betaBody = source.slice(betaStart, betaEnd);+ expect(betaBody).toContain('if (isPassiveSharedUserDataInstance()) return;');+ expect(betaBody).toContain('decodeAccessTokenOrgSlug(accessToken)');+ expect(betaBody).not.toContain('shouldAttemptOrgBetaDefault');+ const nonXdStart = source.indexOf('function scheduleNonXdOrgBetaDefault(');+ const nonXdEnd = source.indexOf('\n}\n\n/**\n * 冷启动流程的进程内去重', nonXdStart);+ const nonXdBody = source.slice(nonXdStart, nonXdEnd);+ expect(nonXdBody).toContain('shouldAttemptOrgBetaDefault');+ expect(betaBody).toContain('enableUncustomizedBetaChannel');+ expect(betaBody).toContain('authStateEpoch === input.expectedAuthEpoch');+ expect(source).not.toContain('relaunchForChannelChange');++ const clearIntegrationsStart = source.indexOf('async function clearPerAccountIntegrations(');+ const clearIntegrationsEnd = source.indexOf('\n}', clearIntegrationsStart);+ expect(source.slice(clearIntegrationsStart, clearIntegrationsEnd)).not.toContain(+ 'canaryFlagStore.clear()',+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex ae9d070cfd..eef7dd6197 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -1,892 +1,8 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';-import { shouldTeardownColdStartRuntime } from '../authColdStartBoundary';-/** Regression guard for login progress that is intentionally owned by Electron main. */describe('auth login-flow reset', () => {- const source = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(- /\r\n/g,- '\n',- );- const logoutPolicySource = readFileSync(- resolve(process.cwd(), 'src/main/authAccountLogoutPolicy.ts'),- 'utf8',- ).replace(/\r\n/g, '\n');- const deviceLinkSource = readFileSync(- resolve(process.cwd(), 'src/main/device-link/index.ts'),- 'utf8',- ).replace(/\r\n/g, '\n');- const hookControlSource = readFileSync(- resolve(process.cwd(), 'src/main/hook-control/ipc.ts'),- 'utf8',- ).replace(/\r\n/g, '\n');-- it('clears renderer state, provider cache, and private tickets whenever auth is cleared', () => {- const resetStart = source.indexOf('function resetLoginFlowState(): void {');- const resetEnd = source.indexOf('\n}', resetStart);- const resetBody = source.slice(resetStart, resetEnd);- expect(resetBody).toContain('loginFlowState = null;');- expect(resetBody).toContain('providerConfig = null;');- expect(resetBody).toContain('discoveredMethods = [];');- expect(resetBody).toContain('pendingAccountToken = null;');- expect(resetBody).toContain('pendingLoginTicket = null;');- expect(resetBody).toContain('pendingBindTicket = null;');- expect(resetBody).toContain('pendingSsoVerificationTicket = null;');-- const clearStart = source.indexOf('function clearAuth(');- const clearEnd = source.indexOf('\n}\n\n// ── Public API', clearStart);- const clearBody = source.slice(clearStart, clearEnd);- expect(clearBody).toContain('resetLoginFlowState();');- expect(clearBody).toContain('canaryFlagStore.clear();');- });-- it('keeps successful personal credentials private until the region choice and excludes saved-account activation', () => {- const start = source.indexOf('async function finishFreshLogin(');- const finish = source.slice(start, source.indexOf('async function runLoginAction(', start));- expect(finish).toContain('discoverPersonalLoginOrganization(outcome.membership');- expect(finish.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)')).toBeGreaterThan(finish.indexOf('await discoverPersonalLoginOrganization'));- expect(finish).toContain('pendingPersonalLogin = { outcome, realm: personalRealm }');- expect(finish).toContain('personalLoginAvailable: true');- expect(finish).not.toContain('pendingAuthRealm = discovery.region');- expect(finish).toContain('return completeLogin(outcome, expectedLoginFlowEpoch)');- const lookupStart = source.indexOf('async function lookupOrganizationRealm(');- const lookup = source.slice(lookupStart, source.indexOf('async function completeLogin(', lookupStart));- expect(lookup).not.toContain('pendingAuthRealm =');- const continueStart = source.indexOf("if (action.type === 'cancel-sso-realm')");- const continueBody = source.slice(continueStart, source.indexOf('if (!providerConfig)', continueStart));- expect(continueBody).toContain('pendingAuthRealm = personal.realm');- expect(continueBody).toContain('await completeLogin(personal.outcome, actionLoginFlowEpoch)');- expect(continueBody).not.toContain('finishFreshLogin(');- const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm')");- const confirmBody = source.slice(confirmStart, continueStart);- expect(confirmBody.indexOf('pendingPersonalLogin = null')).toBeLessThan(confirmBody.indexOf('pendingAuthRealm = confirmation.targetRegion'));- expect(confirmBody).toContain('pendingAccountRefreshToken = null');- expect(source.slice(0, source.indexOf('async function acceptLoginOutcome('))).not.toContain('await finishFreshLogin(');- expect(source).toContain("await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch)");- const reset = source.slice(source.indexOf('function resetLoginFlowState()'), source.indexOf('function clearAuth('));- expect(reset).toContain('pendingPersonalLogin = null');- expect(reset).toContain('handledLoginEmail = null');- });-- it('keeps the login-epoch guard and does not resurrect the legacy feishu token chain', () => {- const completeStart = source.indexOf('async function completeLogin(');- const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);- const completeBody = source.slice(completeStart, completeEnd);- expect(completeBody).toContain(- 'if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch)',- );- expect(completeBody).toContain('notifyRenderer();');- // 防复活:主机飞书 token 链已随 refresh-feishu 退役(2026-07-17),- // authManager 不得再接 FeishuTokenManager(飞书授权归 xd-feishu 意识- // 的 OAuth broker 通道)。- expect(source).not.toContain('getFeishuService');- expect(source).not.toContain('setJwt(');- });-- it('requires confirmation only when enterprise discovery crosses the build region', () => {- const start = source.indexOf("if (action.type === 'discover-sso-org') {");- expect(start).toBeGreaterThan(-1);- const body = source.slice(- start,- source.indexOf("\n if (action.type === 'request-code')", start),- );- expect(body).toContain('const methods = ssoOrgDiscoveryToMethods(discovery)');- expect(body).toContain('if (discovery.region !== AUTH_REGION)');- expect(body).toContain("type: 'realm-switch-required'");- expect(body).toContain("type: 'discovery-loaded'");- expect(body).toContain("email: ''");- // 唯一 SSO 不在 main 里套 start-browser:否则 renderer 要等整段浏览器- // 授权结束才拿得到下一步,确认框会卡住。waiting 投影归 renderer。- expect(body).not.toContain('soleAutoStartSsoMethod');- expect(body).not.toContain("type: 'start-browser'");-- // 跨区连接只有 confirm action 才写入 start-browser 白名单;弹窗阶段不能- // 通过伪造 connectionId 直接跳过确认。- const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm') {");- const confirmBody = source.slice(- confirmStart,- source.indexOf("\n if (action.type === 'cancel-sso-realm')", confirmStart),- );- expect(confirmBody).toContain('discoveredMethods = confirmation.methods;');- expect(confirmBody).toContain("type: 'discovery-loaded'");- expect(confirmBody).not.toContain('soleAutoStartSsoMethod');- expect(confirmBody).not.toContain("type: 'start-browser'");- });-- it('pins personal login to the build realm and clears stale realm before organization discovery', () => {- const discoveryStart = source.indexOf('async function discoverOrganizationRealm(');- const discoveryBody = source.slice(discoveryStart, source.indexOf('\n}', discoveryStart));- expect(discoveryBody).toContain('pendingAuthRealm = null;');-- const actionStart = source.indexOf('async function runLoginAction(');- expect(actionStart).toBeGreaterThan(-1);- const actionPreamble = source.slice(- actionStart,- source.indexOf('const stateBeforeAction', actionStart),- );- expect(actionPreamble).toContain("action.type === 'discover'");- expect(actionPreamble).toContain("action.type === 'request-code'");- expect(actionPreamble).toContain("action.type === 'verify-code'");- expect(actionPreamble).toContain("action.type === 'start-browser' && action.kind === 'social'");- expect(actionPreamble).toContain('? AUTH_REGION');- expect(actionPreamble).toContain('const client = createAuthClient(loginRealm);');-- const personalActionSetup = source.slice(- source.indexOf('if (!providerConfig) await loadLoginProviders', actionStart),- source.indexOf("if (action.type === 'discover')", actionStart),- );- expect(personalActionSetup).toContain(- "if (startsBuildRealmFlow && action.type !== 'request-code') pendingAuthRealm = loginRealm;",- );- });-- it('keeps cross-region email choices gated and preserves SSO after failed personal code sending', () => {- const discover = source.slice(- source.indexOf("if (action.type === 'discover') {"),- source.indexOf("if (action.type === 'discover-sso-org') {"),- );- expect(discover).toContain('discoverEmailLogin(action.email');- expect(discover.indexOf('discoveredMethods = [];')).toBeLessThan(discover.indexOf('await discoverEmailLogin'));- expect(discover).toContain('discoverOrganizationRealm(domain, actionLoginFlowEpoch)');- expect(discover).toContain('pendingAuthRealm = region;');- expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(discover.indexOf('discoveredMethods = methods;'));- expect(source).toContain("email: confirmation.email ?? ''");- const requestStart = source.indexOf("if (action.type === 'request-code') {");- const request = source.slice(requestStart, source.indexOf("if (action.type === 'verify-code') {", requestStart));- expect(request.indexOf('pendingAuthRealm = AUTH_REGION;')).toBeGreaterThan(request.indexOf('await client.requestCode('));- expect(request).toContain('discoveredMethods = [];');- });-- it('does not leave expired private tickets on a screen that can only reuse them', () => {- expect(source).toContain("'INVALID_LOGIN_TICKET',");- expect(source).toContain("'INVALID_BIND_TICKET',");- expect(source).toContain("'INVALID_SSO_VERIFICATION_TICKET',");- expect(source).toContain('const errorState = loginPreparingErrorState(');- expect(source).toContain('? errorState');- });-- it('keeps account access tokens in memory while persisting only encrypted refresh sessions', () => {- expect(source).toContain(- "const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'cindy_auth_account_refresh_token';",- );- expect(source).toContain('let pendingAccountToken: string | null = null;');- expect(source).toContain('client.exchangeAccountMembership(accountToken, action.accountId)');- expect(source).toContain("const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';");- expect(source).toContain('client.refreshAccount(current.accountRefreshToken)');- expect(source).toContain('client.logoutAccount(pair.accountToken)');- expect(source).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY');- expect(source).not.toContain('writeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY');- expect(source).not.toContain('accountToken: accountAccessToken');-- const completeStart = source.indexOf('async function completeLogin(');- const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);- expect(source.slice(completeStart, completeEnd)).toContain('pendingAccountToken = null;');-- const logoutStart = source.indexOf('export async function logout()');- const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);- const logoutBody = source.slice(logoutStart, logoutEnd);- expect(logoutBody).toContain('accessToken: currentAccessToken');- expect(logoutBody).not.toContain('pendingAccountToken');-- const revokeStart = source.indexOf('function revokeLoggedOutAccountBestEffort(');- const revokeEnd = source.indexOf('\n}\n\nexport async function logout()', revokeStart);- expect(source.slice(revokeStart, revokeEnd)).toContain('token: input.accessToken');-- const getterStart = source.indexOf('export function getAccessToken(): string | null {');- const getterEnd = source.indexOf('\n}', getterStart);- const getterBody = source.slice(getterStart, getterEnd);- expect(getterBody).toContain('return accessToken;');- expect(getterBody).not.toContain('accountAccessToken');- });-- it('keeps saved account metadata fresh after profile edits and Passport sync', () => {- expect(source).toContain('const AUTH_ACCOUNT_VAULT_VERSION = 2 as const;');- expect(source).toContain(- "const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY = 'cindy_auth_account_logout_tombstones_v1';",- );- expect(source).toContain('const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION = 1 as const;');- expect(source).toContain('const logoutAuthEpoch = authStateEpoch;');- expect(source).toContain("'Logout was superseded by a newer auth action'");- expect(source).toContain('validateBeforeCommit: isLogoutStillCurrent');- expect(source).toContain('shouldClearOnFailure: isLogoutStillCurrent');- const writePassportStart = source.indexOf('function writePassportSessionToVault(');- const writePassportEnd = source.indexOf(- '\n}\n\n/** Persist a rotated Passport',- writePassportStart,- );- const writePassportBody = source.slice(writePassportStart, writePassportEnd);- expect(writePassportBody).toContain('reconcileSavedAccountMetadata(vault');- expect(writePassportBody).toContain("passportMode: 'replace-passport'");- expect(writePassportBody).toContain('loggedOutKeys.has(accountVaultKey(input.realm');-- const readStart = source.indexOf('function readAuthAccountVault(');- const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);- const readBody = source.slice(readStart, readEnd);- expect(readBody).toContain('persistedVersion !== 1');- expect(readBody).toContain('version: AUTH_ACCOUNT_VAULT_VERSION');-- const writeStart = source.indexOf('function writeAuthAccountVault(');- const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);- const writeBody = source.slice(writeStart, writeEnd);- expect(writeBody).toContain('JSON.stringify({ ...vault, version: 1 })');- expect(writeBody).toContain('older client can');- expect(writeBody).toContain('writeAuthAccountLogoutTombstones(vault)');- expect(writeBody.indexOf('writeAuthAccountLogoutTombstones(vault)')).toBeLessThan(- writeBody.indexOf('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY'),- );-- const logoutTombstoneReadStart = source.indexOf('function readAuthAccountLogoutTombstones(');- const logoutTombstoneReadEnd = source.indexOf(- '\n}\n\nfunction writeAuthAccountLogoutTombstones',- logoutTombstoneReadStart,- );- const logoutTombstoneReadBody = source.slice(logoutTombstoneReadStart, logoutTombstoneReadEnd);- expect(logoutTombstoneReadBody).toContain('parseDesktopAccountKey(key)');- expect(logoutTombstoneReadBody).toContain('isAtomicPersistedSecretAbsent');- expect(logoutTombstoneReadBody).toContain('if (options.recoverInvalid) return [];');-- const logoutTombstoneWriteStart = source.indexOf('function writeAuthAccountLogoutTombstones(');- const logoutTombstoneWriteEnd = source.indexOf(- '\n}\n\nfunction accountVaultKey',- logoutTombstoneWriteStart,- );- expect(source.slice(logoutTombstoneWriteStart, logoutTombstoneWriteEnd)).toContain(- 'JSON.stringify({ version: AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION, accountKeys })',- );-- const readLogoutKeysStart = readBody.indexOf('persistedLogoutKeys =');- expect(readLogoutKeysStart).toBeGreaterThan(-1);- expect(readBody).toContain('recoverInvalid: options.recoverInvalid');- expect(readBody).toContain('if (options.allowUnreadable) return emptyAuthAccountVault();');- expect(readBody).toContain('new Set([...persistedLogoutKeys, ...embeddedLogoutKeys])');- expect(readBody).not.toContain('loggedOutKeys.delete(active)');- expect(readBody).toContain(- 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',- );-- const profileStart = source.indexOf('export async function updateServerProfile(');- const profileEnd = source.indexOf('\n}\n\nexport async function initialize(', profileStart);- const profileBody = source.slice(profileStart, profileEnd);- expect(profileBody).toContain('rememberUpdatedMembershipMetadata(');- expect(profileBody).toContain('membership.passportId ?? currentUser.passportId');- });-- it('serializes saved-account vault mutations across shared-userData processes', () => {- const mutationStart = source.indexOf('async function transactAuthAccountVault');- const mutationEnd = source.indexOf(- '\n}\n\nasync function mutateAuthAccountVault',- mutationStart,- );- const mutationBody = source.slice(mutationStart, mutationEnd);- expect(mutationBody).toContain('withCrossProcessLock(');- expect(mutationBody).toContain(- "status.reason === 'busy' && options.waitWhileBusyAfterRotation",- );- expect(mutationBody).toContain('throw accountVaultLockError(status.reason);');- expect(mutationBody).toContain("if (attempt.kind === 'committed') return attempt.result;");- expect(mutationBody.indexOf('const vault = readAuthAccountVault({')).toBeGreaterThan(- mutationBody.indexOf('if (!status.held)'),- );- const vaultWriteAt = mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault');- expect(vaultWriteAt).toBeGreaterThan(mutationBody.indexOf('await operation(vault);'));- expect(mutationBody.indexOf('await afterPersist(result);')).toBeGreaterThan(vaultWriteAt);- expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);');- expect(mutationBody).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)');- expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);');- expect(mutationBody).toContain(- 'writeAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutRaw)',- );- expect(mutationBody).toContain('readAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)');- expect(mutationBody).toContain('replaceUnreadableLogoutTombstones:');- expect(mutationBody).toContain('options.replaceUnreadableLogoutTombstones');- expect(mutationBody).toContain(- 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',- );-- for (const helper of [- 'async function rememberResourceSession(',- 'async function replaceResourceSessionIfCurrent(',- 'async function removeRejectedResourceSession(',- 'async function rememberPassportSession(',- 'async function replacePassportSessionIfCurrent(',- 'async function removePassportSessionIfCurrent(',- 'async function rememberUpdatedMembershipMetadata(',- 'async function removeVaultAccount(',- ]) {- const start = source.indexOf(helper);- const end = source.indexOf('\n}\n', start);- expect(start).toBeGreaterThan(-1);- expect(source.slice(start, end)).toContain('mutateAuthAccountVault(');- }- });-- it('filters invalid vault children only for read-only projection', () => {- const readStart = source.indexOf('function readAuthAccountVault(');- const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);- const readBody = source.slice(readStart, readEnd);-- expect(readBody).toContain('if (options.allowUnreadable || options.recoverInvalid) continue;');- expect(readBody).toContain("throw new Error('invalid saved resource credential')");- expect(readBody).toContain("throw new Error('invalid saved Passport credential')");- expect(readBody).toContain("throw new Error('invalid saved Passport membership')");- expect(readBody).toContain("throw new Error('invalid logged-out account key')");- expect(readBody).toContain('memberships.length !== item.memberships.length');- expect(readBody).toContain('allowUnreadableLogoutTombstones?: boolean');- expect(readBody).toContain('if (options.allowUnreadableLogoutTombstones) {');- expect(readBody).toContain(- 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',- );- });-- it('recovers invalid Desktop vault content only for a completed explicit login', () => {- const readStart = source.indexOf('function readAuthAccountVault(');- const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);- const readBody = source.slice(readStart, readEnd);- const unreadableBranch = readBody.slice(- readBody.indexOf('if (raw === null)'),- readBody.indexOf('try {'),- );- expect(unreadableBranch).not.toContain('recoverInvalid');- expect(readBody).toContain('options.allowUnreadable || options.recoverInvalid');-- const transactionStart = source.indexOf('async function transactAuthAccountVault');- const transactionEnd = source.indexOf(- '\n}\n\nasync function mutateAuthAccountVault',- transactionStart,- );- const transactionBody = source.slice(transactionStart, transactionEnd);- expect(transactionBody).toContain('recoverInvalidForExplicitLogin?: boolean');- expect(transactionBody).toContain('recoverInvalid: options.recoverInvalidForExplicitLogin');-- const loginStart = source.indexOf('async function commitDesktopLoginSessions(');- const loginEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', loginStart);- const loginBody = source.slice(loginStart, loginEnd);- expect(loginBody).toContain('recoverInvalidForExplicitLogin: true');- expect(loginBody).toContain('waitWhileBusyAfterRotation: true');- const transitionCommit = loginBody.indexOf('await transition.commit();');- const transitionRollback = loginBody.indexOf('await transition.rollback();');- expect(transitionCommit).toBeGreaterThan(loginBody.indexOf('await transactAuthAccountVault('));- expect(transitionRollback).toBeGreaterThan(transitionCommit);- expect(transitionRollback).toBeLessThan(- loginBody.indexOf('recoverInvalidForExplicitLogin: true'),- );- });-- it('replaces unreadable logout tombstones only for explicit login or logout', () => {- const writeStart = source.indexOf('function writeAuthAccountVault(');- const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);- const writeBody = source.slice(writeStart, writeEnd);- expect(writeBody).toContain('replaceUnreadableLogoutTombstones?: boolean');- expect(writeBody).toContain('const previousLogoutUnreadable =');- expect(writeBody).toContain('previousLogoutCiphertext === null');- expect(writeBody).toContain('!options.replaceUnreadableLogoutTombstones');- expect(writeBody).toContain(- 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',- );-- const clearStart = source.indexOf('async function clearAuthAccountVault(');- const clearEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', clearStart);- expect(source.slice(clearStart, clearEnd)).toContain(- 'writeAuthAccountVaultOrThrow(vault, { replaceUnreadableLogoutTombstones: true });',- );- });-- it('atomically replaces the aggregate saved-account vault', () => {- const writeStart = source.indexOf('function writeAtomicSafe(');- const writeEnd = source.indexOf('\n}\n\nfunction removeAtomicSafeOrThrow', writeStart);- const writeBody = source.slice(writeStart, writeEnd);- expect(writeBody).toContain('atomicWriteFileSync(');- expect(writeBody).toContain("safeStorage.encryptString(value).toString('base64')");-- const readStart = source.indexOf('function readAtomicSafe(');- const readEnd = source.indexOf('\n}\n\nfunction isAtomicPersistedSecretAbsent', readStart);- expect(source.slice(readStart, readEnd)).toContain('fs.readFileSync(`${filepath}.bak`');-- const clearStart = source.indexOf('function removeAtomicSafeOrThrow(');- const clearEnd = source.indexOf('\n}\n\nfunction removeSafe(', clearStart);- const clearBody = source.slice(clearStart, clearEnd);- expect(clearBody.indexOf('`${filepath}.bak`')).toBeLessThan(clearBody.indexOf('filepath])'));- });-- it('waits through a busy vault lock after the server has rotated a credential', () => {- const rotatedCredentialHelpers = [- ['async function rememberResourceSession(', '\n}\n\ntype ResourceSessionReplacementResult'],- [- 'async function replaceResourceSessionIfCurrent(',- '\n}\n\ntype RejectedResourceSessionRemovalResult',- ],- ['async function replacePassportSessionIfCurrent(', '\n}\n\n/** Delete a rejected Passport'],- ['async function commitDesktopRefreshCredentials(', '\n}\n\n/**\n * Account refresh tokens'],- ] as const;-- for (const [startMarker, endMarker] of rotatedCredentialHelpers) {- const start = source.indexOf(startMarker);- const end = source.indexOf(endMarker, start);- expect(start).toBeGreaterThan(-1);- expect(source.slice(start, end)).toContain('waitWhileBusyAfterRotation: true');- }- });-- it('fails a Desktop account switch before owner teardown and rolls back under the vault lock', () => {- const completeStart = source.indexOf('async function completeLogin(');- const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);- const completeBody = source.slice(completeStart, completeEnd);- const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');- const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');- const ownerCommit = completeBody.indexOf('await withCloudOwnerCommit({');- expect(vaultTransaction).toBeGreaterThan(-1);- expect(durableSession).toBeGreaterThan(vaultTransaction);- expect(durableSession).toBeGreaterThan(-1);- expect(ownerCommit).toBeGreaterThan(durableSession);- expect(completeBody.indexOf('restorePersistedAuthSessionIfCurrent(')).toBeGreaterThan(- ownerCommit,- );- expect(completeBody.indexOf('rollback: () => {')).toBeGreaterThan(ownerCommit);- expect(completeBody.slice(ownerCommit)).not.toContain(- 'writePersistedAuthSession(outcome.refreshToken',- );- });-- it('invalidates pending add-account actions without cancelling an accepted login commit', () => {- const runStart = source.indexOf('async function runLoginAction(');- expect(runStart).toBeGreaterThan(-1);- const runEnd = source.indexOf('\n}\n\nexport async function dispatchLoginAction', runStart);- const runBody = source.slice(runStart, runEnd);- expect(runBody).toContain('const actionLoginFlowEpoch = loginFlowEpoch;');- expect(runBody).toContain('assertLoginFlowCurrent(actionLoginFlowEpoch);');- expect(runBody).toContain("code: 'AUTH_FLOW_SUPERSEDED'");-- const completeStart = source.indexOf('async function completeLogin(');- const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);- const completeBody = source.slice(completeStart, completeEnd);- expect(completeBody).toContain('expectedLoginFlowEpoch = loginFlowEpoch');- expect(completeBody).toContain('loginFlowEpoch !== expectedLoginFlowEpoch');- expect(completeBody).toContain(- 'const releaseLoginFlowCommit = sealLoginFlowCommit(expectedLoginFlowEpoch);',- );- expect(completeBody).toContain('releaseLoginFlowCommit();');- const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');- const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');- const teardown = completeBody.indexOf('await accountSwitchTeardown(');- expect(vaultTransaction).toBeGreaterThan(-1);- expect(durableSession).toBeGreaterThan(vaultTransaction);- expect(completeBody.lastIndexOf('assertTransitionCurrent();', teardown)).toBeLessThan(teardown);- expect(completeBody).toContain('restorePersistedAuthSessionIfCurrent(');-- const cancelStart = source.indexOf('export function cancelAddAccountLogin(): void {');- const cancelEnd = source.indexOf('\n}\n\nexport function getCurrentDataOwnerId', cancelStart);- const cancelBody = source.slice(cancelStart, cancelEnd);- expect(cancelBody).toContain('if (isLoginFlowCommitSealed(loginFlowEpoch))');- expect(cancelBody).toContain('loginFlowEpoch += 1;');- expect(cancelBody.indexOf('isLoginFlowCommitSealed')).toBeLessThan(- cancelBody.indexOf('loginFlowEpoch += 1;'),- );- });-- it('single-flights Passport refresh and rejects cross-realm personal account switching', () => {- const helperStart = source.indexOf('async function refreshPassportSessionSingleFlight(');- const helperEnd = source.indexOf(- '\n}\n\nasync function rememberUpdatedMembershipMetadata',- helperStart,- );- const helperBody = source.slice(helperStart, helperEnd);- expect(helperBody).toContain('passportAccountRefreshFlights.get(key)');- expect(helperBody).toContain('replacePassportSessionIfCurrent({');- expect(helperBody).toContain('removePassportSessionIfCurrent(');- expect(helperBody.indexOf("error.code === 'DEVICE_MISMATCH'")).toBeLessThan(- helperBody.indexOf('removePassportSessionIfCurrent('),- );- expect(source).toContain("'write-failed'");- expect(source).toContain("'CREDENTIAL_STORE_UNAVAILABLE'");- expect(source).toContain('isPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)');- expect(source).toContain('readAuthAccountVault({ allowUnreadable: true })');- expect(source).toContain('writeAuthAccountVaultOrThrow(vault');-- const syncStart = source.indexOf('export async function syncSavedAccounts()');- const syncEnd = source.indexOf('\n}\n\nexport async function switchSavedAccount', syncStart);- const syncBody = source.slice(syncStart, syncEnd);- expect(syncBody).toContain('refreshPassportSessionSingleFlight(');-- const switchStart = syncEnd;- const switchEnd = source.indexOf(- '\n}\n\nexport async function beginAddAccountLogin',- switchStart,- );- const switchBody = source.slice(switchStart, switchEnd);- const policyGuard = switchBody.indexOf('!canRestoreAuthSessionForMembership(');- const commitRealm = switchBody.indexOf('pendingAuthRealm = realm;');- expect(policyGuard).toBeGreaterThan(-1);- expect(commitRealm).toBeGreaterThan(policyGuard);- expect(switchBody).toContain('refreshPassportSessionSingleFlight(');- expect(switchBody).toContain('refreshSavedResourceSession({');- expect(switchBody).not.toContain('client.refresh(resource.refreshToken)');- expect(switchBody).not.toContain('removeVaultAccount(parsedKey)');- expect(switchBody).toContain("'REGION_MISMATCH'");- expect(switchBody).toContain('const switchLoginFlowEpoch = loginFlowEpoch;');- expect(switchBody).toContain(- "await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch, {",- );- expect(switchBody).toContain('restoreLoggedOutAccount: false');- expect(switchBody).toContain('accountToLogOut: options.accountToLogOut');- expect(switchBody).toContain('validateBeforeCommit: options.validateBeforeCommit');-- const completeLoginStart = source.indexOf('async function completeLogin(');- const completeLoginEnd = source.indexOf(- '\n}\n\nasync function runLoginAction',- completeLoginStart,- );- const completeLoginBody = source.slice(completeLoginStart, completeLoginEnd);- expect(completeLoginBody).toContain('validateBeforeCommit?: (loginEpoch: number) => void;');- expect(completeLoginBody).toContain('options.validateBeforeCommit?.(loginEpoch);');- const resourceRefreshStart = source.indexOf('async function refreshSavedResourceSession(');- const resourceRefreshEnd = source.indexOf(- '\n}\n\nfunction readPersistedAuthSession()',- resourceRefreshStart,- );- const resourceRefreshBody = source.slice(resourceRefreshStart, resourceRefreshEnd);- expect(resourceRefreshBody).toContain('runRefreshWithReplacementRetry<RefreshAttemptData>(');- expect(resourceRefreshBody).toContain(- 'readAuthAccountVault().resources[input.accountKey]?.refreshToken',- );- expect(resourceRefreshBody).toContain('replaceResourceSessionIfCurrent({');- expect(resourceRefreshBody).toContain('removeRejectedResourceSession({');- expect(resourceRefreshBody).toContain("if (removal === 'stale')");- expect(resourceRefreshBody).toContain("'AUTH_FLOW_SUPERSEDED'");- expect(resourceRefreshBody).toContain("lastRefreshError.code === 'DEVICE_MISMATCH'");- });-- it('keeps account refresh out of resource-token cold-start initialization', () => {- const initializeStart = source.indexOf('export async function initialize(');- const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);- const initializeBody = source.slice(initializeStart, initializeEnd);- const authenticatedFastPath = initializeBody.indexOf('if (accessToken && currentUser)');-- expect(authenticatedFastPath).toBeGreaterThan(-1);- expect(initializeBody).toContain('removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);');- expect(initializeBody).not.toContain('refreshAccount');- expect(initializeBody).not.toContain('restoreAccountSelection');- });-- it('returns a committed local session before reading or refreshing cloud credentials', () => {- const initializeStart = source.indexOf('export async function initialize(');- const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);- const initializeBody = source.slice(initializeStart, initializeEnd);- const localGuard = initializeBody.indexOf("getActiveAppSession().mode === 'local'");- const refreshTokenRead = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');-- expect(localGuard).toBeGreaterThan(-1);- expect(refreshTokenRead).toBeGreaterThan(localGuard);- expect(initializeBody.slice(localGuard, refreshTokenRead)).toContain(- 'return snapshotAuthState();',- );- });-- it('preserves compatibility and vault generations before cold-start refresh', () => {- const helperStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');- const helperEnd = source.indexOf('\n}\n\nfunction readPersistedRefreshToken', helperStart);- const helperBody = source.slice(helperStart, helperEnd);- expect(helperBody).toContain('authAccountVaultLockPath()');- expect(helperBody).toContain("label: 'auth-account-vault-reconcile'");- expect(helperBody).toContain('vault.resources[vault.activeAccountKey]');- expect(helperBody).toContain('if (!session)');- expect(helperBody).toContain('writePersistedAuthSessionOrThrow(');- expect(helperBody).toContain('return session;');-- const candidatesStart = source.indexOf('function readStoredRefreshTokenCandidates');- const candidatesEnd = source.indexOf(- '\n}\n\nfunction readPersistedAccountDeletionReceipt',- candidatesStart,- );- const candidatesBody = source.slice(candidatesStart, candidatesEnd);- expect(candidatesBody).toContain('readPersistedRefreshToken(realm)');- expect(candidatesBody).toContain('vault.resources[vault.activeAccountKey]');- expect(candidatesBody).toContain('activeResource.refreshToken');-- const commitStart = source.indexOf('async function commitDesktopRefreshCredentials');- const commitEnd = source.indexOf(- '\n}\n\n/**\n * Account refresh tokens have no replay grace.',- commitStart,- );- const commitBody = source.slice(commitStart, commitEnd);- expect(commitBody).toContain('vault.resources[key]?.refreshToken === requestedRefreshToken');-- const deadStart = source.indexOf('async function clearConfirmedDeadRefreshTokens');- const deadEnd = source.indexOf('\n}\n\n/**\n * replacement-retry', deadStart);- const deadBody = source.slice(deadStart, deadEnd);- expect(deadBody).toContain('await mutateAuthAccountVault((vault) => {');- expect(deadBody).toContain('deadTokens.includes(activeResource.refreshToken)');- expect(deadBody).toContain('delete vault.resources[activeKey];');- expect(deadBody).toContain('vault.activeAccountKey = null;');-- const listStart = source.indexOf('export function listSavedAccounts()');- const listEnd = source.indexOf('\n}\n\nexport async function syncSavedAccounts', listStart);- const listBody = source.slice(listStart, listEnd);- expect(listBody).toContain(- 'const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;',- );-- const initializeStart = source.indexOf('export async function initialize(');- const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);- const initializeBody = source.slice(initializeStart, initializeEnd);- const reconcileAt = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');- const refreshAt = initializeBody.indexOf(- 'runColdStartRefreshFlow(storedToken, persistedSession.realm)',- );- expect(reconcileAt).toBeGreaterThan(-1);- expect(refreshAt).toBeGreaterThan(reconcileAt);- });-- it('keeps a durable signed-out owner across a crash between vault and session cleanup', () => {- expect(source).toContain('signedOutAt?: number;');-- const clearStart = source.indexOf('async function clearAuthAccountVault(');- const clearEnd = source.indexOf('\n}\n\nfunction persistLogoutTombstoneOnly', clearStart);- const clearBody = source.slice(clearStart, clearEnd);- expect(clearBody).toContain('withCrossProcessLock(');- expect(clearBody).toContain("label: 'auth-account-vault-clear'");- expect(clearBody).toContain('const vault = emptyAuthAccountVault();');- expect(clearBody).toContain('vault.activeAccountKey = null;');- expect(clearBody).toContain('vault.resources = {};');- expect(clearBody).toContain('vault.passports = {};');- expect(clearBody).toContain('vault.signedOutAt = Date.now();');- expect(clearBody.indexOf('writeAuthAccountVaultOrThrow(vault);')).toBeLessThan(- clearBody.indexOf('await afterPersist();'),- );-- const tombstoneStart = source.indexOf('async function persistLogoutTombstoneOnly(');- const tombstoneEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', tombstoneStart);- const tombstoneBody = source.slice(tombstoneStart, tombstoneEnd);- expect(tombstoneBody).toContain("label: 'auth-account-logout-tombstone'");- expect(tombstoneBody).toContain('readAuthAccountLogoutTombstones({ recoverInvalid: true })');- expect(tombstoneBody).toContain('writeAuthAccountLogoutTombstones(vault)');- expect(tombstoneBody).not.toContain('writeAuthAccountVaultOrThrow');-- const reconcileStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');- const reconcileEnd = source.indexOf(- '\n}\n\nfunction readPersistedRefreshToken',- reconcileStart,- );- const reconcileBody = source.slice(reconcileStart, reconcileEnd);- const tombstoneGuard = reconcileBody.indexOf("typeof vault.signedOutAt === 'number'");- expect(tombstoneGuard).toBeGreaterThan(-1);- expect(reconcileBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneGuard);- expect(reconcileBody.indexOf('return null;')).toBeGreaterThan(tombstoneGuard);- expect(reconcileBody.indexOf('writePersistedAuthSessionOrThrow(')).toBeGreaterThan(- tombstoneGuard,- );-- const refreshCommitStart = source.indexOf('async function commitDesktopRefreshCredentials(');- const refreshCommitEnd = source.indexOf(- '\n}\n\n/**\n * Account refresh tokens',- refreshCommitStart,- );- const refreshCommitBody = source.slice(refreshCommitStart, refreshCommitEnd);- expect(refreshCommitBody).toContain("typeof vault.signedOutAt !== 'number'");- expect(refreshCommitBody).toContain('!loggedOutAccountKeySet(vault).has(key)');- expect(refreshCommitBody.indexOf('!loggedOutAccountKeySet(vault).has(key)')).toBeGreaterThan(- refreshCommitBody.indexOf('options.allowUnclaimedVault === true'),- );-- const resourceWriteStart = source.indexOf('function writeResourceSessionToVault(');- const resourceWriteEnd = source.indexOf(- '\n}\n\nasync function rememberPassportSession',- resourceWriteStart,- );- const resourceWriteBody = source.slice(resourceWriteStart, resourceWriteEnd);- expect(resourceWriteBody).toContain('if (options.markActive !== false) {');- expect(resourceWriteBody).toContain('delete vault.signedOutAt;');- expect(resourceWriteBody).toContain(- 'if (options.restoreLoggedOutAccount) restoreLoggedOutVaultAccount(vault, key);',- );-- const loginCommitStart = source.indexOf('async function commitDesktopLoginSessions(');- const loginCommitEnd = source.indexOf(- '\n}\n\n/** Persist a rotated Passport',- loginCommitStart,- );- const loginCommitBody = source.slice(loginCommitStart, loginCommitEnd);- expect(loginCommitBody).toContain('if (!input.passportId) {');- expect(loginCommitBody).toContain('delete vault.signedOutAt;');- expect(loginCommitBody).toContain('removeLoggedOutVaultAccount(vault, input.accountToLogOut)');-- const logoutStart = source.indexOf('export async function logout(): Promise<void> {');- const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);- const logoutBody = source.slice(logoutStart, logoutEnd);- const tombstoneCommit = logoutBody.indexOf('await mutateAuthAccountVault(');- const ownerTeardown = logoutBody.indexOf('await withAccountFreeOwnerCommit({');- expect(tombstoneCommit).toBeGreaterThan(-1);- expect(logoutBody).toContain('savedVaultWasUnreadable');- expect(logoutBody).toContain('await persistLogoutTombstoneOnly(currentIdentity.accountKey);');- expect(logoutBody).not.toContain('clearAuthAccountVault((vault) => {');- expect(logoutBody).toContain('savedVaultHasUnreadableLogoutTombstones');- expect(logoutBody).toContain(- 'const candidateAccountKeys = savedVaultHasUnreadableLogoutTombstones',- );- expect(logoutBody).toContain(- 'replaceUnreadableLogoutTombstones: savedVaultHasUnreadableLogoutTombstones',- );- expect(logoutBody).toContain('removeLoggedOutVaultAccount(vault, currentIdentity)');- expect(logoutBody).toContain('vault.signedOutAt = Date.now();');- expect(logoutBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneCommit);- expect(ownerTeardown).toBeGreaterThan(tombstoneCommit);- expect(logoutBody).toContain('preservePersistedRefreshToken: true');- });-- it('logs out only the current saved account and advances to the next restorable account', () => {- expect(source).toContain('loggedOutAccountKeys?: string[];');-- const removalStart = logoutPolicySource.indexOf('export function removeLoggedOutVaultAccount<');- const removalBody = logoutPolicySource.slice(removalStart);- expect(removalBody).toContain('delete vault.resources[identity.accountKey];');- expect(removalBody).toContain('loggedOutKeys.add(identity.accountKey);');- expect(removalBody).toContain('const hasRestorableSibling =');- expect(removalBody).toContain('if (hasRestorableSibling) return null;');- expect(removalBody).toContain('delete vault.passports[passportKey];');-- const summariesStart = source.indexOf('function savedAccountSummaries(');- const summariesEnd = source.indexOf('\n}\n\nexport function listSavedAccounts', summariesStart);- const summariesBody = source.slice(summariesStart, summariesEnd);- expect(summariesBody).toContain('const loggedOutKeys = loggedOutAccountKeySet(vault);');- expect(summariesBody).toContain(- 'if (!loggedOutKeys.has(key)) byKey.set(key, resource.metadata);',- );- expect(summariesBody).toContain('return rightUsed - leftUsed');-- const logoutStart = source.indexOf('export async function logout(): Promise<void> {');- const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);- const logoutBody = source.slice(logoutStart, logoutEnd);- const candidateLoop = logoutBody.indexOf(- 'for (const candidateAccountKey of candidateAccountKeys)',- );- const terminalSignOut = logoutBody.indexOf('await mutateAuthAccountVault(');- expect(candidateLoop).toBeGreaterThan(-1);- expect(logoutBody).toContain('await switchSavedAccount(candidateAccountKey, {');- expect(logoutBody).toContain('accountToLogOut: currentIdentity');- expect(logoutBody).toContain('validateBeforeCommit: (loginEpoch) => {');- expect(logoutBody).toContain('assertLogoutStillCurrent(loginEpoch);');- expect(logoutBody).toContain('candidateTransitionEpoch = loginEpoch;');- expect(logoutBody).toContain('assertLogoutTransitionStillCurrent(candidateTransitionEpoch);');- expect(logoutBody).toContain('assertLogoutStillCurrent();');- expect(logoutBody).toContain('if (isUnavailableSavedAccountError(error)) continue;');- expect(logoutBody).toContain('isRetryableSavedAccountSwitchError(error)');- const retryableSwitchStart = source.indexOf('function isRetryableSavedAccountSwitchError(');- const retryableSwitchEnd = source.indexOf(- '\n}\n\nfunction revokeLoggedOutAccountBestEffort',- retryableSwitchStart,- );- const retryableSwitchBody = source.slice(retryableSwitchStart, retryableSwitchEnd);- expect(retryableSwitchBody).toContain('error.statusCode === 429');- expect(retryableSwitchBody).toContain("'RATE_LIMITED'");- expect(logoutBody.indexOf('return;', candidateLoop)).toBeLessThan(terminalSignOut);- expect(terminalSignOut).toBeGreaterThan(candidateLoop);- expect(logoutBody).not.toContain('revokeSavedSessionsBestEffort');- });-- it('activates a restored realm only after the refreshed membership passes build policy', () => {- const initializeStart = source.indexOf('export async function initialize(');- const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);- const initializeBody = source.slice(initializeStart, initializeEnd);- expect(initializeBody).toContain('await loadClientEndpointsForRealm(persistedSession.realm);');- expect(initializeBody).not.toContain('activateClientEndpointRealm(persistedSession.realm);');-- const coldStart = source.indexOf('async function runColdStartRefreshFlow(');- const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);- const coldBody = source.slice(coldStart, coldEnd);- const coldCredentialCommit = coldBody.indexOf('await commitDesktopRefreshCredentials(');- const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');- const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');- expect(coldCredentialCommit).toBeGreaterThan(-1);- expect(coldPolicyGuard).toBeGreaterThan(-1);- expect(coldCredentialCommit).toBeLessThan(coldPolicyGuard);- expect(coldRealmActivation).toBeGreaterThan(coldPolicyGuard);- expect(coldBody).toContain('requestedToken,');- expect(coldBody).toContain('allowUnclaimedVault: true');- expect(coldBody).toContain("epochChanged('before-cold-start-credential-commit')");- expect(coldBody).toContain("credentialCommit !== 'active'");- const inactiveCommit = coldBody.indexOf("credentialCommit !== 'active'");- const activeCandidateRead = coldBody.indexOf(- 'readActiveVaultRefreshCandidate()',- inactiveCommit,- );- const ownershipRetry = coldBody.indexOf('return runColdStartRefreshFlow(', activeCandidateRead);- expect(activeCandidateRead).toBeGreaterThan(inactiveCommit);- expect(ownershipRetry).toBeGreaterThan(activeCandidateRead);- expect(coldBody.slice(inactiveCommit, ownershipRetry)).toContain(- '!attemptedOwnershipTokens.has(nextActiveCandidate.refreshToken)',- );- expect(coldBody).not.toContain(- 'writePersistedAuthSession(refreshData.refreshToken, storedRealm)',- );- expect(coldBody).not.toContain('rememberResourceSession(refreshData');-- const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');- const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);- const refreshBody = source.slice(refreshStart, refreshEnd);- const runtimePolicyGuard = refreshBody.indexOf('!canRestoreAuthSessionForMembership(');- const runtimeRealmActivation = refreshBody.indexOf(- 'activateClientEndpointRealm(refreshRealm);',- );- expect(runtimePolicyGuard).toBeGreaterThan(-1);- expect(runtimeRealmActivation).toBeGreaterThan(runtimePolicyGuard);- expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');- expect(refreshBody).toContain(- "await expireRuntimeAuth(currentUser.id, 'replaced-elsewhere', {",- );- expect(refreshBody).toContain('preservePersistedRefreshToken: true');- });-- it('retries the vault active account after a stale compatibility token fails on cold start', () => {- const coldStart = source.indexOf('async function runColdStartRefreshFlow(');- const coldStartEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', coldStart);- const coldStartBody = source.slice(coldStart, coldStartEnd);- expect(coldStartBody).toContain(- 'const nextActiveCandidate = readActiveVaultRefreshCandidate();',- );- expect(coldStartBody).toContain(- 'cold-start refresh rejected a stale compatibility token; continuing with the vault active account',- );- expect(coldStartBody).toContain(- 'expectedActiveVaultAccountKey: nextActiveCandidate.accountKey',- );- const clearDeadTokens = coldStartBody.indexOf('await clearConfirmedDeadRefreshTokens(');- const staleEpochGuard = coldStartBody.indexOf(- "epochChanged('after-clearing-confirmed-dead-tokens')",- clearDeadTokens,- );- const ownershipRetry = coldStartBody.indexOf(- 'return runColdStartRefreshFlow(',- clearDeadTokens,- );- expect(clearDeadTokens).toBeGreaterThan(-1);- expect(staleEpochGuard).toBeGreaterThan(clearDeadTokens);- expect(ownershipRetry).toBeGreaterThan(staleEpochGuard);- });-- it('unlocks login preparing with the splash startup gate after 30s', () => {- const loadStart = source.indexOf('async function loadLoginProviders(');- const loadEnd = source.indexOf('\n}\n\nasync function discoverOrganizationRealm(', loadStart);- const loadBody = source.slice(loadStart, loadEnd);- expect(loadBody).toContain('await awaitLoginProvidersWithPreparingGate(');- expect(loadBody).toContain('createAuthClient(AUTH_REGION).getProviders()');- // 闸只限时等待,不 abort 在途 getProviders(与 splash 冷启动闸同一语义)。- expect(loadBody).not.toContain('.abort(');-- const getLoginStart = source.indexOf('export async function getLoginState(');- const getLoginEnd = source.indexOf('\n}\n\nasync function completeLogin(', getLoginStart);- const getLoginBody = source.slice(getLoginStart, getLoginEnd);- const waitForOwnerChange = getLoginBody.indexOf('await ownerChangeShellGate.waitForSettled();');- const captureLoginEpoch = getLoginBody.indexOf(- 'const expectedLoginFlowEpoch = loginFlowEpoch;',- );- expect(waitForOwnerChange).toBeGreaterThan(-1);- expect(captureLoginEpoch).toBeGreaterThan(-1);- expect(waitForOwnerChange).toBeLessThan(captureLoginEpoch);- expect(getLoginBody).toContain('await loadLoginProviders(expectedLoginFlowEpoch)');- expect(getLoginBody).toContain('mapLoginProvidersLoadFailure(error)');- });it('does not call teardown for a fresh signed-out/null cold-start session', () => {const teardown = vi.fn();@@ -903,6 +19,7 @@ describe('auth login-flow reset', () => {expect(teardown).not.toHaveBeenCalled();});+it('tears down only an already-committed runtime that crosses an owner boundary', () => {expect(shouldTeardownColdStartRuntime(@@ -923,276 +40,4 @@ describe('auth login-flow reset', () => {),).toBe(true);});-- it('drops a runtime refresh result after logout or a newer login changes auth generation', () => {- const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');- const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);- const refreshBody = source.slice(refreshStart, refreshEnd);- expect(refreshBody).toContain('const refreshEpoch = authStateEpoch;');- expect(refreshBody).toContain("refreshWasSuperseded('after-refresh')");- // 'after-product-me' 守卫点已随产品 /api/user/me 退役(2026-07):refresh- // 与提交之间不再有产品资料网络往返,该迟到窗口不存在了。- expect(refreshBody).not.toContain('/api/user/me');- expect(refreshBody).toContain("refreshWasSuperseded('after-account-switch-teardown')");- expect(refreshBody).toContain("refreshWasSuperseded('after-integration-reload')");- expect(refreshBody).toContain("refreshWasSuperseded('catch')");- expect(refreshBody).toContain('latestSession.refreshToken === requestedToken');- expect(refreshBody).toContain("credentialCommit !== 'active'");-- const helperStart = source.indexOf('async function commitDesktopRefreshCredentials(');- const helperEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', helperStart);- const helperBody = source.slice(helperStart, helperEnd);- expect(helperBody).toContain('vault.activeAccountKey === key');- expect(helperBody).toContain('options.validateBeforeWrite?.()');- expect(helperBody).toContain('canClaimUninitializedVault');- expect(helperBody).toContain('Object.keys(vault.resources).length === 0');- expect(helperBody).toContain('readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)');- expect(helperBody).toContain('markActive: stillOwnsActiveSession');- expect(helperBody).toContain("if (commit === 'active') {");- expect(helperBody).toContain('writePersistedAuthSessionOrThrow(pair.refreshToken, realm);');- });-- it('advances the existing owner generation when login or restoration commits another realm', () => {- for (const [entry, realm] of [- ['async function runColdStartRefreshFlow(', 'storedRealm'],- ['async function completeLogin(', 'committedRealm'],- ]) {- const start = source.indexOf(entry);- expect(start).toBeGreaterThan(-1);- const body = source.slice(start, source.indexOf('\n}\n', start));- const capture = body.indexOf(`const authRealmChanged = ${realm} !== activeAuthRealm;`);- const activate = body.indexOf(`activeAuthRealm = ${realm};`);- const commit = body.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');- expect(capture).toBeGreaterThan(-1);- expect(activate).toBeGreaterThan(capture);- expect(commit).toBeGreaterThan(activate);- }- const start = source.indexOf('function commitCloudAppSession(');- const helper = source.slice(start, source.indexOf('\n}\n', start));- expect(helper).toContain("commitActiveAppSession('cloud', ownerId, authRealmChanged);");- expect(helper).toContain("commitVolatileAppSession('cloud', ownerId, authRealmChanged);");- });-- it('reconnects realm-bound main clients after a runtime realm change commits its new token', () => {- const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');- const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);- const refreshBody = source.slice(refreshStart, refreshEnd);-- expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');- expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');- expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');- expect(refreshBody.match(/commitCloudAppSession\(currentUser.id, authRealmChanged\);/g)).toHaveLength(2);- expect(refreshBody).toContain(- 'const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',- );- expect(refreshBody).toContain(- 'previousUserId !== nextUser.id || authRealmChanged || membershipKindChanged',- );- expect(refreshBody).toContain(- 'if (authRealmChanged || membershipKindChanged) {\n notifyAuthListeners();',- );-- expect(deviceLinkSource).toContain('restartDeviceLinkForAuthRealmChange();');- expect(deviceLinkSource).toContain('void stopArbitrationAndTeardown()');- expect(deviceLinkSource).toContain('authManager.getActiveAuthRealm() !== targetRealm');- expect(hookControlSource).toContain('} else if (realmChanged) {');- expect(hookControlSource).toContain('manager?.sync();');- });-- it('tears down the owner boundary before notifying runtime auth expiry', () => {- const helperStart = source.indexOf('async function expireRuntimeAuth(');- const helperEnd = source.indexOf('\n}\n\n// ── Public API', helperStart);- const helperBody = source.slice(helperStart, helperEnd);- expect(helperBody).toContain('clearAuth({ notify: false,');- expect(helperBody).toContain('await withAccountFreeOwnerCommit({');- expect(helperBody).toContain('authAlreadyCleared: true');- expect(helperBody).toContain('notifySessionExpired(reason);');-- const ownerCommitStart = source.indexOf('async function withAccountFreeOwnerCommit(');- const ownerCommitEnd = source.indexOf(- '\n}\n\nasync function withCloudOwnerCommit(',- ownerCommitStart,- );- const ownerCommitBody = source.slice(ownerCommitStart, ownerCommitEnd);- expect(ownerCommitBody).toContain('beginAppSessionBoundary()');- expect(ownerCommitBody).toContain('notifyRendererAuthBoundaryPending();');- expect(ownerCommitBody).toContain('await accountSwitchTeardown');- expect(ownerCommitBody).toContain('await authSessionTeardown(opts.reason);');- expect(ownerCommitBody).toContain('notifyAuthListeners();');-- const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');- const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);- const refreshBody = source.slice(refreshStart, refreshEnd);- expect(refreshBody).toContain(- 'await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));',- );- expect(refreshBody).not.toContain('clearAuth({ notify: false });');- });-- it('reserves local namespaces before publishing a cloud owner', () => {- const cloudStart = source.indexOf('async function withCloudOwnerCommit(');- const prepareStart = source.indexOf('prepareCommit: async () => {', cloudStart);- const prepareEnd = source.indexOf('\n },\n commit: async () => {', prepareStart);- const prepareBody = source.slice(prepareStart, prepareEnd);-- expect(prepareBody).toContain(- 'rollbackReservation = reserveCloudOwnerData(opts.nextOwnerId, opts.previousOwnerId);',- );- expect(prepareBody.indexOf('reserveCloudOwnerData')).toBeLessThan(- prepareBody.indexOf('await opts.prepareCommit?.();'),- );- expect(source).toContain('await repairStableCloudOwnerDataReservations(currentUser.id);');- expect(source).toContain('if (reservation && !reservation.finalize())');- expect(source).toContain('if (!reservation.rollback())');- expect(source).toContain('if (boundaryCommitApplied || commitApplied) return;');-- const failureStart = source.indexOf(- 'onCommitFailure: ({ commitApplied: boundaryCommitApplied }) => {',- cloudStart,- );- const failureEnd = source.indexOf('\n },\n });', failureStart);- const failureBody = source.slice(failureStart, failureEnd);- expect(failureBody).toContain('if (boundaryCommitApplied || commitApplied) return;');- expect(failureBody.indexOf('if (!reservation.rollback())')).toBeLessThan(- failureBody.indexOf('rollbackReservation = null;'),- );- const finallyStart = source.indexOf(' } finally {', failureEnd);- const finallyBody = source.slice(finallyStart, source.indexOf('\n }\n', finallyStart));- expect(finallyBody).toContain('if (!committed && !commitApplied)');-- const repairStart = source.indexOf(- 'function repairStableCloudOwnerDataReservationsWhileLocked(',- );- const repairEnd = source.indexOf(- '\n}\n\nasync function repairStableCloudOwnerDataReservations(',- repairStart,- );- const repairBody = source.slice(repairStart, repairEnd);- expect(repairBody).toContain('reserveCommittedLocalProfileDataOwnerDetailed(');- expect(repairBody).toContain(- 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',- );- expect(repairBody).toContain(- 'reserveCommittedLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',- );- expect(repairBody).toContain(- 'reserveCommittedLegacyNativeProviderAuthOwner(authoritativeOwnerId)',- );- expect(repairBody).not.toContain('reserveLocalProfileDataOwnerDetailed(');- expect(repairBody).not.toContain('reserveLegacyNativeProviderAuthOwnerDetailed(ownerId)');- expect(repairBody).toContain('remains authenticated with local adoption fail-closed');- expect(repairBody).not.toContain('throw new Error');- const serializedRepairStart = source.indexOf(- 'async function repairStableCloudOwnerDataReservations(',- );- const serializedRepairEnd = source.indexOf(- '\n}\n\nfunction commitCloudAppSession(',- serializedRepairStart,- );- const serializedRepairBody = source.slice(serializedRepairStart, serializedRepairEnd);- expect(serializedRepairBody).toContain('withStableOwnerBoundaryMutation(ownerId');- expect(serializedRepairBody).toContain(- 'repairStableCloudOwnerDataReservationsWhileLocked(ownerId)',- );-- const reserveStart = source.indexOf('function reserveCloudOwnerData(');- const reserveEnd = source.indexOf(- '\n}\n\nfunction repairStableCloudOwnerDataReservationsWhileLocked(',- reserveStart,- );- const reserveBody = source.slice(reserveStart, reserveEnd);- expect(reserveBody).toContain(- 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',- );- expect(reserveBody).toContain(- 'reserveLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',- );- expect(reserveBody).toContain(- 'releaseLocalProfileDataOwner(\n profileReservationOwnerId,',- );- expect(reserveBody).toContain(- "if (nativeReservation.status === 'claimed' && nativeReservation.claimToken)",- );- expect(reserveBody).not.toContain(- "profileReservation.status === 'claimed' &&\n nativeReservation.status === 'claimed'",- );- expect(reserveBody).toContain('const authoritativeOwnerId = profileReservation.ownerId;');- expect(reserveBody).toContain(- 'reserveLegacyNativeProviderAuthOwnerDetailed(authoritativeOwnerId)',- );- expect(reserveBody).toContain(- "throw new Error('local profile and native provider ownership reservations disagree')",- );- expect(reserveBody).toContain(- 'finalize: () => recoverCloudOwnerDataReservations(authoritativeOwnerId)',- );-- const migrationStart = source.indexOf(- 'async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Promise<void> {',- );- const migrationEnd = source.indexOf(- '\n}\n\nasync function finishColdStartSignedOut(',- migrationStart,- );- const migrationBody = source.slice(migrationStart, migrationEnd);- expect(migrationBody).toContain(- 'if (!(await repairStableCloudOwnerDataReservations(ownerId))) return;',- );- expect(migrationBody.indexOf('repairStableCloudOwnerDataReservations')).toBeLessThan(- migrationBody.indexOf('migrateLocalNativeProviderAuthBindings'),- );- });-- it('synchronizes canary flags on every path that establishes a new auth identity', () => {- expect(source).not.toContain('canaryFlagStore.sync(false)');- expect(source.match(/scheduleCanaryFlagSync\(\{/g)).toHaveLength(3);- expect(source.match(/scheduleXdOrgBetaDefault\(\{/g)).toHaveLength(3);- expect(source.match(/scheduleNonXdOrgBetaDefault\(\{/g)).toHaveLength(1);- expect(source).toContain("getClientEndpoint('oauthBrokerApiBaseUrl')");- expect(source).toContain("apiFetch('/api/user/feature-flags'");-- const syncStart = source.indexOf('function scheduleCanaryFlagSync(');- const syncEnd = source.indexOf(- '\n}\n\n/**\n * 登录态落地后为 xd 组织补一次设备级 beta 默认值',- syncStart,- );- expect(syncEnd).toBeGreaterThan(syncStart);- const syncBody = source.slice(syncStart, syncEnd);- expect(syncBody).toContain("if (outcome.kind === 'synced')");- expect(syncBody).toContain('notifyRenderer();');-- const completeStart = source.indexOf('async function completeLogin(');- const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);- const completeBody = source.slice(completeStart, completeEnd);- const acceptedUser = completeBody.indexOf('currentUser = nextUser;');- const ownerCommit = completeBody.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');- const clearPreviousFlag = completeBody.indexOf('canaryFlagStore.clear();', acceptedUser);- expect(acceptedUser).toBeGreaterThan(-1);- expect(clearPreviousFlag).toBeGreaterThan(acceptedUser);- expect(ownerCommit).toBeGreaterThan(clearPreviousFlag);- expect(completeBody.slice(acceptedUser, clearPreviousFlag)).toContain(- 'if (!isPassiveSharedUserDataInstance()) {',- );-- const betaStart = source.indexOf('function scheduleXdOrgBetaDefault(');- const betaEnd = source.indexOf('function scheduleNonXdOrgBetaDefault(', betaStart);- expect(betaEnd).toBeGreaterThan(betaStart);- const betaBody = source.slice(betaStart, betaEnd);- expect(betaBody).toContain('if (isPassiveSharedUserDataInstance()) return;');- expect(betaBody).toContain('decodeAccessTokenOrgSlug(accessToken)');- expect(betaBody).not.toContain('shouldAttemptOrgBetaDefault');- const nonXdStart = source.indexOf('function scheduleNonXdOrgBetaDefault(');- const nonXdEnd = source.indexOf('\n}\n\n/**\n * 冷启动流程的进程内去重', nonXdStart);- const nonXdBody = source.slice(nonXdStart, nonXdEnd);- expect(nonXdBody).toContain('shouldAttemptOrgBetaDefault');- expect(betaBody).toContain('enableUncustomizedBetaChannel');- expect(betaBody).toContain('authStateEpoch === input.expectedAuthEpoch');- expect(source).not.toContain('relaunchForChannelChange');-- const clearIntegrationsStart = source.indexOf('async function clearPerAccountIntegrations(');- const clearIntegrationsEnd = source.indexOf('\n}', clearIntegrationsStart);- expect(source.slice(clearIntegrationsStart, clearIntegrationsEnd)).not.toContain(- 'canaryFlagStore.clear()',- );- });});diff --git a/apps/desktop/src/main/__tests__/loginScenarioHarness.contract.test.ts b/apps/desktop/src/main/__tests__/loginScenarioHarness.contract.test.tsnew file mode 100644index 0000000000..0526611315--- /dev/null+++ b/apps/desktop/src/main/__tests__/loginScenarioHarness.contract.test.ts@@ -0,0 +1,64 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * 桌面端登录 scenario harness 接线测试(implementation-plan Step 0 WHAT4 / SC-1)。+ *+ * 分两层:+ * 1. 注入点静态断言(authManager.ts 依赖重、不宜整模块加载,沿用本目录+ * authLoginFlowReset.test.ts 的读源码断言模式):guard 形态与「真实 client ++ * scenario fetch 构造参数注入」形态不许漂移。+ * 2. guard 行为断言(fixtures 包纯函数):app.isPackaged(devModeActive=false)+ * 下 harness 全部失效——production-mode 断言。+ */+const authManagerSource = readFileSync(+ resolve(process.cwd(), 'src/main/authManager.ts'),+ 'utf8',+);++const viteMainConfigSource = readFileSync(+ resolve(process.cwd(), 'vite.main.config.ts'),+ 'utf8',+);+++describe('authManager 注入点(静态源码断言)', () => {+ it('经静态 import 使用 fixtures(main 禁运行时动态 import)', () => {+ expect(authManagerSource).toContain(+ "import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures'",+ );+ expect(authManagerSource).not.toContain("import('@cindy/auth-client/fixtures')");+ });++ it('guard 写死为 !app.isPackaged + XDT_LOGIN_SCENARIO(附录 A 值域 env)', () => {+ expect(authManagerSource).toContain('devModeActive: !app.isPackaged');+ expect(authManagerSource).toContain('scenario: process.env.XDT_LOGIN_SCENARIO');+ });++ it('注入形态 = 真实 CindyAuthClient + fetch 构造参数(scenarioFetch ?? 真 fetch)', () => {+ expect(authManagerSource).toContain(+ 'fetch: scenarioFetch ?? (async (input, init) => net.fetch(input, init as RequestInit))',+ );+ // 不替换 client、不 fake 方法:注入点仍是唯一的 new CindyAuthClient 构造+ expect(authManagerSource.match(/new CindyAuthClient\(/g)).toHaveLength(1);+ });++ it('vite.main.config 挂了生产 stub alias(build-time 排除双保险)', () => {+ expect(viteMainConfigSource).toContain("mode === 'production'");+ expect(viteMainConfigSource).toContain("find: '@cindy/auth-client/fixtures'");+ expect(viteMainConfigSource).toContain('loginScenarios.production-stub.ts');+ });++ it('vite.main.config 保留显式空 Team ID,不让 .env 旧值重新启用 Touch ID', () => {+ expect(viteMainConfigSource).toContain(+ "Object.prototype.hasOwnProperty.call(process.env, key)",+ );+ expect(viteMainConfigSource).toContain(+ "readMainEnvPreservingEmpty('CINDY_WEBAUTHN_APPLE_TEAM_ID').trim()",+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts b/apps/desktop/src/main/__tests__/loginScenarioHarness.test.tsindex 181d4527bf..a532146b89 100644--- a/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts+++ b/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts@@ -1,66 +1,8 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import { CindyAuthClient } from '@cindy/auth-client';import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';-/**- * 桌面端登录 scenario harness 接线测试(implementation-plan Step 0 WHAT4 / SC-1)。- *- * 分两层:- * 1. 注入点静态断言(authManager.ts 依赖重、不宜整模块加载,沿用本目录- * authLoginFlowReset.test.ts 的读源码断言模式):guard 形态与「真实 client +- * scenario fetch 构造参数注入」形态不许漂移。- * 2. guard 行为断言(fixtures 包纯函数):app.isPackaged(devModeActive=false)- * 下 harness 全部失效——production-mode 断言。- */-const authManagerSource = readFileSync(- resolve(process.cwd(), 'src/main/authManager.ts'),- 'utf8',-);-const viteMainConfigSource = readFileSync(- resolve(process.cwd(), 'vite.main.config.ts'),- 'utf8',-);--describe('authManager 注入点(静态源码断言)', () => {- it('经静态 import 使用 fixtures(main 禁运行时动态 import)', () => {- expect(authManagerSource).toContain(- "import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures'",- );- expect(authManagerSource).not.toContain("import('@cindy/auth-client/fixtures')");- });-- it('guard 写死为 !app.isPackaged + XDT_LOGIN_SCENARIO(附录 A 值域 env)', () => {- expect(authManagerSource).toContain('devModeActive: !app.isPackaged');- expect(authManagerSource).toContain('scenario: process.env.XDT_LOGIN_SCENARIO');- });-- it('注入形态 = 真实 CindyAuthClient + fetch 构造参数(scenarioFetch ?? 真 fetch)', () => {- expect(authManagerSource).toContain(- 'fetch: scenarioFetch ?? (async (input, init) => net.fetch(input, init as RequestInit))',- );- // 不替换 client、不 fake 方法:注入点仍是唯一的 new CindyAuthClient 构造- expect(authManagerSource.match(/new CindyAuthClient\(/g)).toHaveLength(1);- });-- it('vite.main.config 挂了生产 stub alias(build-time 排除双保险)', () => {- expect(viteMainConfigSource).toContain("mode === 'production'");- expect(viteMainConfigSource).toContain("find: '@cindy/auth-client/fixtures'");- expect(viteMainConfigSource).toContain('loginScenarios.production-stub.ts');- });-- it('vite.main.config 保留显式空 Team ID,不让 .env 旧值重新启用 Touch ID', () => {- expect(viteMainConfigSource).toContain(- "Object.prototype.hasOwnProperty.call(process.env, key)",- );- expect(viteMainConfigSource).toContain(- "readMainEnvPreservingEmpty('CINDY_WEBAUTHN_APPLE_TEAM_ID').trim()",- );- });-});-describe('guard 行为(production-mode 断言)', () => {it('app.isPackaged(devModeActive=false)→ 即使 env 设置了 scenario 也恒 null', () => {expect(diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.contract.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.contract.test.tsnew file mode 100644index 0000000000..01fbe4928e--- /dev/null+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.contract.test.ts@@ -0,0 +1,150 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++describe('注入接线(源码级守卫)', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/makerSendTransaction.ts'),+ 'utf8',+ );++ it('说明只进 wire payload,落库走 persistUserMessage.content', () => {+ expect(source).toContain(+ 'deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true',+ );+ // 注入链:normalized → withHandoff → withPlanReconcile → withGoalInactiveNote+ // → 来源说明 → 客户端说明(元信息都在交接段之前)。+ expect(source).toContain('prependNoteToWireUserMessage(withGoalInactiveNote as HandoffWireMessage, messageSourceNote)');+ // 环境说明经 wireNoteMemory 去重后再前置(内容没变就不重复),链路位置不变。+ expect(source).toContain("prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, plannedNotes['client-environment'])");+ expect(source).toContain('deps.planRepeatableWireNotes?.(sessionId, repeatableNotes, { force: pendingHandoff !== null })');+ expect(source).toContain('readWireSourceDevice(so.sourceDevice)');+ expect(source).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');+ // 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进+ // 用户消息、污染界面显示的原话。+ expect(source).toContain('content: persistUserMessage.content');+ expect(source).not.toMatch(/content:\s*outgoing/);+ });++ it('来源判据经 deps 注入,不在事务里直接 import ALS', () => {+ // 只看 import 与调用形态 —— deps 字段的注释里会提到这个函数名,那不算直连。+ expect(source).not.toMatch(/from '\.\.\/device-link\/invoke-context/);+ expect(source).not.toMatch(/isMobileControllerInvoke\s*\(/);+ });++ it('注释不得把平台值说成安全边界(平台由对端 hello 自报,无服务端校验)', () => {+ const files = [+ 'src/main/device-link/invoke-context.ts',+ 'src/main/device-link/controllerPlatform.ts',+ 'src/main/maker-ipc/makerSendTransaction.ts',+ ].map((rel) => readFileSync(resolve(process.cwd(), rel), 'utf8'));+ for (const text of files) {+ expect(text).not.toContain('不可伪造');+ }+ // 三处都必须显式声明它只用于体验分流。+ expect(files[0]).toContain('不是安全 / 鉴权 / 权限边界');+ expect(files[1]).toContain('仅体验分流,不是安全边界');+ expect(files[2]).toContain('不是安全判据');+ });++ it('装配处每次调用现取,不提前求值缓存', () => {+ const register = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ expect(register).toContain('isMobileClientInvoke: () => isMobileControllerInvoke()');+ });+});+++describe('排队 / 插入两条路径的接线(源码级守卫)', () => {+ const register = readFileSync(resolve(process.cwd(), 'src/main/maker-ipc/register.ts'), 'utf8');+ const coordinator = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/agent-input-coordinator.ts'),+ 'utf8',+ );+ const transaction = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/makerSendTransaction.ts'),+ 'utf8',+ );+ const sendHandler = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/sessionSendHandler.ts'),+ 'utf8',+ );++ it('enqueue 与 steer 两个 IPC 边界都盖章,编辑时按编辑者重新盖章', () => {+ // 手机会话页所有发送都走这两条,只在 invoke context 里读来源实际读不到(review P1)。+ // 第三处是排队编辑(两个编辑入口共用 stampQueuedEditProvenance)。+ const stamps = register.match(/stampMobileClientOrigin\(/g) ?? [];+ expect(stamps.length).toBe(3);+ expect(register.match(/stampQueuedEditProvenance\(updated, remote, editor\)/g)?.length).toBe(2);+ expect(register).toContain('isMobileControllerInvoke(),');+ });++ it('device-link provenance is stamped at both queue input boundaries', () => {+ const stamps = register.match(/stampTrustedDeviceLinkQueuedOrigin\(/g) ?? [];+ expect(stamps.length).toBe(3);+ expect(register).toContain('deviceLinkInvoke,');+ // 设备来源与 device-link 标记同点盖章(两处 IPC 边界)。+ expect(register.match(/deviceLinkInvoke,\r?\n\s+readDeviceLinkInvokeSourceDevice\(\),/g)?.length).toBe(2);+ });++ it('直连 maker:send / maker:steer 在 IPC 边界按 invoke context 盖设备来源', () => {+ expect(register.match(/stampDirectSendSourceDevice\([^)]*readDeviceLinkInvokeSourceDevice\(\)\)/g)?.length).toBe(2);+ });++ it('coordinator 在 drain 与 steer 两处都透传设备来源', () => {+ expect(coordinator).toContain('...(head.sourceDevice ? { sourceDevice: head.sourceDevice } : {})');+ expect(coordinator).toContain('...(item.sourceDevice ? { sourceDevice: item.sourceDevice } : {})');+ expect(coordinator).toContain('...(!isHostGeneratedSteerItem(item) && item.origin ? { sourceOrigin: item.origin } : {})');+ });++ it('coordinator 在 drain 与 steer 两处都透传', () => {+ const passes = coordinator.match(/fromMobileClient: true \} : \{\}\)/g) ?? [];+ expect(passes.length).toBe(2);+ });++ it('coordinator drain carries device-link provenance into the send transaction', () => {+ expect(coordinator).toContain('fromDeviceLinkClient: true } : {})');+ expect(transaction).toContain('requestedSendOpts.fromDeviceLinkClient === true');+ });++ it('send 事务认 async context 与透传值两个来源', () => {+ expect(transaction).toContain(+ "deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true",+ );+ });++ it('steer 投递也注入说明,且只进 wire payload', () => {+ expect(register).toContain("isMobileControllerInvoke() || so.fromMobileClient === true");+ expect(register).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');+ expect(register).toContain('prependNoteToWireUserMessage(normalized as HandoffWireMessage, steerSourceNote)');+ // steer 与 send 事务共用同一份环境说明去重记忆,投递成功后才记为已发送。+ expect(register).toContain("prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerPlannedNotes['client-environment'])");+ expect(register).toContain('steerNotePlan?.commit()');+ expect(register).toContain('readWireSourceDevice(so.sourceDevice)');+ expect(register).toContain('await sess.steer(steerPayload as never');+ });++ it('直连 maker:send 的 wire sendOpts 必须消毒', () => {+ expect(sendHandler).toContain(+ 'attachMainOwnedInputBoundary(sendOpts, mainOwnedBoundaryStamp)',+ );+ });++ it('直连 maker:steer 的 wire sendOpts 同样必须消毒', () => {+ // 这个 channel 在 device-link allowlist 里开放,sendOpts 是调用方可控输入 ——+ // 不剥的话传 `{ fromMobileClient: true }` 就能让非手机轮次收到伪造的手机说明+ // (review P1/P2 各报一次)。契约与 maker:send 一致:该字段只由 main 盖章。+ expect(register).toContain(+ 'const sanitizedSendOpts = attachMainOwnedInputBoundary(',+ );+ expect(register).toContain('stripMainOnlySendOpts(sendOpts)');+ // coordinator 的内部调用**不得**被消毒 —— 那条路的 sendOpts 是 main 构造的透传值。+ expect(register).toContain('steerToAgent: (sessionId, message, sendOpts) => {');+ expect(register).toContain('const expectedText = trustedDesktopSteerText.getStore();');+ });+});diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.tsindex c99dac63c5..4e34450167 100644--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts@@ -3,8 +3,6 @@* device-link/invoke-context 的可信度说明)、设备盖章、wire 注入形态、以及「只进喂给* agent 的内容、不进落库原话」这条不变量的源码级守卫。*/-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, it, expect, beforeEach } from 'vitest';import {@@ -317,60 +315,6 @@ describe('shouldPrependMobileClientPromptNote(内置命令旁路)', () => {});});-describe('注入接线(源码级守卫)', () => {- const source = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/makerSendTransaction.ts'),- 'utf8',- );-- it('说明只进 wire payload,落库走 persistUserMessage.content', () => {- expect(source).toContain(- 'deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true',- );- // 注入链:normalized → withHandoff → withPlanReconcile → withGoalInactiveNote- // → 来源说明 → 客户端说明(元信息都在交接段之前)。- expect(source).toContain('prependNoteToWireUserMessage(withGoalInactiveNote as HandoffWireMessage, messageSourceNote)');- // 环境说明经 wireNoteMemory 去重后再前置(内容没变就不重复),链路位置不变。- expect(source).toContain("prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, plannedNotes['client-environment'])");- expect(source).toContain('deps.planRepeatableWireNotes?.(sessionId, repeatableNotes, { force: pendingHandoff !== null })');- expect(source).toContain('readWireSourceDevice(so.sourceDevice)');- expect(source).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');- // 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进- // 用户消息、污染界面显示的原话。- expect(source).toContain('content: persistUserMessage.content');- expect(source).not.toMatch(/content:\s*outgoing/);- });-- it('来源判据经 deps 注入,不在事务里直接 import ALS', () => {- // 只看 import 与调用形态 —— deps 字段的注释里会提到这个函数名,那不算直连。- expect(source).not.toMatch(/from '\.\.\/device-link\/invoke-context/);- expect(source).not.toMatch(/isMobileControllerInvoke\s*\(/);- });-- it('注释不得把平台值说成安全边界(平台由对端 hello 自报,无服务端校验)', () => {- const files = [- 'src/main/device-link/invoke-context.ts',- 'src/main/device-link/controllerPlatform.ts',- 'src/main/maker-ipc/makerSendTransaction.ts',- ].map((rel) => readFileSync(resolve(process.cwd(), rel), 'utf8'));- for (const text of files) {- expect(text).not.toContain('不可伪造');- }- // 三处都必须显式声明它只用于体验分流。- expect(files[0]).toContain('不是安全 / 鉴权 / 权限边界');- expect(files[1]).toContain('仅体验分流,不是安全边界');- expect(files[2]).toContain('不是安全判据');- });-- it('装配处每次调用现取,不提前求值缓存', () => {- const register = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),- 'utf8',- );- expect(register).toContain('isMobileClientInvoke: () => isMobileControllerInvoke()');- });-});-describe('stampMobileClientOrigin(IPC 边界盖章)', () => {it('手机来源盖上标记,返回新对象不改入参', () => {// 显式标出可选字段:真实入参是 AgentInputQueuedMessage(该字段是可选的),@@ -527,92 +471,3 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {expect(stripMainOnlySendOpts('x')).toBe('x');});});--describe('排队 / 插入两条路径的接线(源码级守卫)', () => {- const register = readFileSync(resolve(process.cwd(), 'src/main/maker-ipc/register.ts'), 'utf8');- const coordinator = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/agent-input-coordinator.ts'),- 'utf8',- );- const transaction = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/makerSendTransaction.ts'),- 'utf8',- );- const sendHandler = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/sessionSendHandler.ts'),- 'utf8',- );-- it('enqueue 与 steer 两个 IPC 边界都盖章,编辑时按编辑者重新盖章', () => {- // 手机会话页所有发送都走这两条,只在 invoke context 里读来源实际读不到(review P1)。- // 第三处是排队编辑(两个编辑入口共用 stampQueuedEditProvenance)。- const stamps = register.match(/stampMobileClientOrigin\(/g) ?? [];- expect(stamps.length).toBe(3);- expect(register.match(/stampQueuedEditProvenance\(updated, remote, editor\)/g)?.length).toBe(2);- expect(register).toContain('isMobileControllerInvoke(),');- });-- it('device-link provenance is stamped at both queue input boundaries', () => {- const stamps = register.match(/stampTrustedDeviceLinkQueuedOrigin\(/g) ?? [];- expect(stamps.length).toBe(3);- expect(register).toContain('deviceLinkInvoke,');- // 设备来源与 device-link 标记同点盖章(两处 IPC 边界)。- expect(register.match(/deviceLinkInvoke,\r?\n\s+readDeviceLinkInvokeSourceDevice\(\),/g)?.length).toBe(2);- });-- it('直连 maker:send / maker:steer 在 IPC 边界按 invoke context 盖设备来源', () => {- expect(register.match(/stampDirectSendSourceDevice\([^)]*readDeviceLinkInvokeSourceDevice\(\)\)/g)?.length).toBe(2);- });-- it('coordinator 在 drain 与 steer 两处都透传设备来源', () => {- expect(coordinator).toContain('...(head.sourceDevice ? { sourceDevice: head.sourceDevice } : {})');- expect(coordinator).toContain('...(item.sourceDevice ? { sourceDevice: item.sourceDevice } : {})');- expect(coordinator).toContain('...(!isHostGeneratedSteerItem(item) && item.origin ? { sourceOrigin: item.origin } : {})');- });-- it('coordinator 在 drain 与 steer 两处都透传', () => {- const passes = coordinator.match(/fromMobileClient: true \} : \{\}\)/g) ?? [];- expect(passes.length).toBe(2);- });-- it('coordinator drain carries device-link provenance into the send transaction', () => {- expect(coordinator).toContain('fromDeviceLinkClient: true } : {})');- expect(transaction).toContain('requestedSendOpts.fromDeviceLinkClient === true');- });-- it('send 事务认 async context 与透传值两个来源', () => {- expect(transaction).toContain(- "deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true",- );- });-- it('steer 投递也注入说明,且只进 wire payload', () => {- expect(register).toContain("isMobileControllerInvoke() || so.fromMobileClient === true");- expect(register).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');- expect(register).toContain('prependNoteToWireUserMessage(normalized as HandoffWireMessage, steerSourceNote)');- // steer 与 send 事务共用同一份环境说明去重记忆,投递成功后才记为已发送。- expect(register).toContain("prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerPlannedNotes['client-environment'])");- expect(register).toContain('steerNotePlan?.commit()');- expect(register).toContain('readWireSourceDevice(so.sourceDevice)');- expect(register).toContain('await sess.steer(steerPayload as never');- });-- it('直连 maker:send 的 wire sendOpts 必须消毒', () => {- expect(sendHandler).toContain(- 'attachMainOwnedInputBoundary(sendOpts, mainOwnedBoundaryStamp)',- );- });-- it('直连 maker:steer 的 wire sendOpts 同样必须消毒', () => {- // 这个 channel 在 device-link allowlist 里开放,sendOpts 是调用方可控输入 ——- // 不剥的话传 `{ fromMobileClient: true }` 就能让非手机轮次收到伪造的手机说明- // (review P1/P2 各报一次)。契约与 maker:send 一致:该字段只由 main 盖章。- expect(register).toContain(- 'const sanitizedSendOpts = attachMainOwnedInputBoundary(',- );- expect(register).toContain('stripMainOnlySendOpts(sendOpts)');- // coordinator 的内部调用**不得**被消毒 —— 那条路的 sendOpts 是 main 构造的透传值。- expect(register).toContain('steerToAgent: (sessionId, message, sendOpts) => {');- expect(register).toContain('const expectedText = trustedDesktopSteerText.getStore();');- });-});diff --git a/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.contract.test.ts b/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.contract.test.tsnew file mode 100644index 0000000000..4452e39b6c--- /dev/null+++ b/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.contract.test.ts@@ -0,0 +1,23 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++describe('official profile writer wiring', () => {+ it('index 对正式 profile 落地 XDT_OFFICIAL_SHARED_PROFILE,migrate 在备份前拒绝', () => {+ const indexSource = readFileSync(resolve(process.cwd(), 'src/main/index.ts'), 'utf8');+ const migrateSource = readFileSync(+ resolve(process.cwd(), 'src/main/localDb/migrate.ts'),+ 'utf8',+ );+ expect(indexSource).toContain("process.env.XDT_OFFICIAL_SHARED_PROFILE = '1'");+ const refuseIdx = migrateSource.indexOf('shouldRefuseOfficialProfileWriterMigration({');+ const prepareIdx = migrateSource.indexOf('prepareBackupDiskSpace(');+ const backupIdx = migrateSource.indexOf('await backupDb(');+ expect(refuseIdx).toBeGreaterThan(-1);+ expect(prepareIdx).toBeGreaterThan(refuseIdx);+ expect(backupIdx).toBeGreaterThan(refuseIdx);+ });+});diff --git a/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.test.ts b/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.test.tsindex 0c3f1f48fa..8d482e92aa 100644--- a/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.test.ts+++ b/apps/desktop/src/main/__tests__/officialProfileMigrationPolicy.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import {@@ -53,20 +51,3 @@ describe('officialProfileWriterMigrationMessage', () => {expect(message).toContain('--isolated=');});});--describe('official profile writer wiring', () => {- it('index 对正式 profile 落地 XDT_OFFICIAL_SHARED_PROFILE,migrate 在备份前拒绝', () => {- const indexSource = readFileSync(resolve(process.cwd(), 'src/main/index.ts'), 'utf8');- const migrateSource = readFileSync(- resolve(process.cwd(), 'src/main/localDb/migrate.ts'),- 'utf8',- );- expect(indexSource).toContain("process.env.XDT_OFFICIAL_SHARED_PROFILE = '1'");- const refuseIdx = migrateSource.indexOf('shouldRefuseOfficialProfileWriterMigration({');- const prepareIdx = migrateSource.indexOf('prepareBackupDiskSpace(');- const backupIdx = migrateSource.indexOf('await backupDb(');- expect(refuseIdx).toBeGreaterThan(-1);- expect(prepareIdx).toBeGreaterThan(refuseIdx);- expect(backupIdx).toBeGreaterThan(refuseIdx);- });-});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.contract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.contract.test.tsnew file mode 100644index 0000000000..a269492c96--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.contract.test.ts@@ -0,0 +1,32 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++describe("codexImageAuthBinding", () => {+++ it('bootstrap statically injects auth before Ghost IPC registration', () => {+ const bootstrap = fs.readFileSync(+ path.resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),+ 'utf-8',+ );+ const brain = fs.readFileSync(+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf-8',+ );++ expect(bootstrap).toContain("from './maker-host/anthropic-responses-bridge-host.js';");+ expect(bootstrap).toContain('getChatgptBridgeAuth,');+ expect(bootstrap).toContain('invalidateChatgptBridgeAuth,');+ expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeGreaterThan(-1);+ expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeLessThan(+ bootstrap.indexOf('registerGhostIpc();'),+ );+ expect(brain).not.toMatch(+ /import\(\s*['"]\.\.\/maker-host\/anthropic-responses-bridge-host\.js['"]\s*\)/,+ );+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.tsindex d7e37f08a0..419d85ae3f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts@@ -1,5 +1,3 @@-import fs from 'node:fs';-import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -27,26 +25,4 @@ describe('codexImageAuthBinding', () => {});expect(onAuthFailure).toHaveBeenCalledOnce();});-- it('bootstrap statically injects auth before Ghost IPC registration', () => {- const bootstrap = fs.readFileSync(- path.resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),- 'utf-8',- );- const brain = fs.readFileSync(- path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),- 'utf-8',- );-- expect(bootstrap).toContain("from './maker-host/anthropic-responses-bridge-host.js';");- expect(bootstrap).toContain('getChatgptBridgeAuth,');- expect(bootstrap).toContain('invalidateChatgptBridgeAuth,');- expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeGreaterThan(-1);- expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeLessThan(- bootstrap.indexOf('registerGhostIpc();'),- );- expect(brain).not.toMatch(- /import\(\s*['"]\.\.\/maker-host\/anthropic-responses-bridge-host\.js['"]\s*\)/,- );- });});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.contract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.contract.test.tsnew file mode 100644index 0000000000..81c54f7071--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.contract.test.ts@@ -0,0 +1,69 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++describe('legacy Ghost recovery acknowledgement orchestration', () => {+ it('routes startup migration through the stable-owner task instead of timing callbacks', () => {+ const source = fs.readFileSync(+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf8',+ ).replace(/\r\n?/g, '\n');++ expect(source).toContain('stableOwnerPostCommitTask = async (reason, scope) => {');+ expect(source).not.toContain("scheduleBuiltinReconcile('startup')");+ expect(source).not.toContain("scheduleBuiltinReconcile('auth-change')");+ expect(source).not.toContain('ghost oauth startup reconciliation failed');+ expect(source).not.toContain('queueMicrotask(() => {\n void reconcileGhostOauthAccountsForActiveOwner()');+ expect(source).toContain("return migrationNeedsRetry ? 'retry-pending' : 'completed';");+ expect(source).toContain('migrationNeedsRetry ||= approvalNeedsRetry;');+ expect(source).toContain('approvalNeedsRetry = true;');+ expect(source).toContain("if (outcome === 'deferred') return outcome;");+ expect(source).toContain('if (dataOwnerId !== null) {');+ expect(source).toContain('activeOwnerScopeKey() !== scope.scopeKey');+ expect(source).toContain('getActiveAppSession().dataOwnerId !== scope.dataOwnerId');+ expect(source).toContain('const activationOutcome = activateGhostsAndMigrateLegacyAccounts();');+ expect(source).toContain("return outcome === 'failed'");+ expect(source).toContain(+ "const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {",+ );+ expect(+ source.match(/if \(migration\.retryPending\) legacyMigrationNeedsRetry = true;/g),+ ).toHaveLength(3);+ expect(+ source.match(/catch \(err\) \{\n\s+legacyMigrationNeedsRetry = true;/g),+ ).toHaveLength(3);+ expect(source).toContain(+ "return legacyMigrationNeedsRetry ? 'retry-pending' : 'completed';",+ );+ expect(source).toContain(+ "outcome === 'retry-pending' || activationOutcome === 'retry-pending'",+ );+ expect(source).toContain("(error as NodeJS.ErrnoException).code === 'ENOENT'");+ expect(source).toContain('LEGACY_MIGRATION_RETRYABLE_FAILURE');+ });++ it('keeps both retry-pending and deterministic backfill failures in the durable marker', () => {+ const source = fs.readFileSync(+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf8',+ ).replace(/\r\n?/g, '\n');+ const start = source.indexOf(+ 'const backfill = await getGhostManager().backfillRecoveredLegacyGhosts(',+ );+ const end = source.indexOf("log.warn('recovered legacy ghost backfill pass failed'", start);+ const acknowledgementBlock = source.slice(start, end);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(acknowledgementBlock).toContain('const pending = new Set(backfill.pending ?? []);');+ expect(acknowledgementBlock).toContain('const failed = new Set(backfill.failed);');+ expect(acknowledgementBlock).toContain(+ 'recoveredLegacyIds.filter((id) => !pending.has(id) && !failed.has(id))',+ );+ expect(acknowledgementBlock).not.toContain('captureRecoveredLegacyNamespace(');+ expect(acknowledgementBlock).toContain('await acknowledgeRecoveredLegacyGhosts(');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.tsindex 1ad567b525..1bd9a39511 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts@@ -1,4 +1,3 @@-import fs from 'node:fs';import path from 'node:path';import { describe, expect, it, vi } from 'vitest';@@ -118,66 +117,3 @@ describe('legacy account activation source boundaries', () => {expect(fixture.data.size).toBe(0);});});--describe('legacy Ghost recovery acknowledgement orchestration', () => {- it('routes startup migration through the stable-owner task instead of timing callbacks', () => {- const source = fs.readFileSync(- path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),- 'utf8',- ).replace(/\r\n?/g, '\n');-- expect(source).toContain('stableOwnerPostCommitTask = async (reason, scope) => {');- expect(source).not.toContain("scheduleBuiltinReconcile('startup')");- expect(source).not.toContain("scheduleBuiltinReconcile('auth-change')");- expect(source).not.toContain('ghost oauth startup reconciliation failed');- expect(source).not.toContain('queueMicrotask(() => {\n void reconcileGhostOauthAccountsForActiveOwner()');- expect(source).toContain("return migrationNeedsRetry ? 'retry-pending' : 'completed';");- expect(source).toContain('migrationNeedsRetry ||= approvalNeedsRetry;');- expect(source).toContain('approvalNeedsRetry = true;');- expect(source).toContain("if (outcome === 'deferred') return outcome;");- expect(source).toContain('if (dataOwnerId !== null) {');- expect(source).toContain('activeOwnerScopeKey() !== scope.scopeKey');- expect(source).toContain('getActiveAppSession().dataOwnerId !== scope.dataOwnerId');- expect(source).toContain('const activationOutcome = activateGhostsAndMigrateLegacyAccounts();');- expect(source).toContain("return outcome === 'failed'");- expect(source).toContain(- "const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {",- );- expect(- source.match(/if \(migration\.retryPending\) legacyMigrationNeedsRetry = true;/g),- ).toHaveLength(3);- expect(- source.match(/catch \(err\) \{\n\s+legacyMigrationNeedsRetry = true;/g),- ).toHaveLength(3);- expect(source).toContain(- "return legacyMigrationNeedsRetry ? 'retry-pending' : 'completed';",- );- expect(source).toContain(- "outcome === 'retry-pending' || activationOutcome === 'retry-pending'",- );- expect(source).toContain("(error as NodeJS.ErrnoException).code === 'ENOENT'");- expect(source).toContain('LEGACY_MIGRATION_RETRYABLE_FAILURE');- });-- it('keeps both retry-pending and deterministic backfill failures in the durable marker', () => {- const source = fs.readFileSync(- path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),- 'utf8',- ).replace(/\r\n?/g, '\n');- const start = source.indexOf(- 'const backfill = await getGhostManager().backfillRecoveredLegacyGhosts(',- );- const end = source.indexOf("log.warn('recovered legacy ghost backfill pass failed'", start);- const acknowledgementBlock = source.slice(start, end);-- expect(start).toBeGreaterThanOrEqual(0);- expect(end).toBeGreaterThan(start);- expect(acknowledgementBlock).toContain('const pending = new Set(backfill.pending ?? []);');- expect(acknowledgementBlock).toContain('const failed = new Set(backfill.failed);');- expect(acknowledgementBlock).toContain(- 'recoveredLegacyIds.filter((id) => !pending.has(id) && !failed.has(id))',- );- expect(acknowledgementBlock).not.toContain('captureRecoveredLegacyNamespace(');- expect(acknowledgementBlock).toContain('await acknowledgeRecoveredLegacyGhosts(');- });-});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.contract.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.contract.test.tsnew file mode 100644index 0000000000..7f3996092a--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.contract.test.ts@@ -0,0 +1,72 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++describe("performMessageDeletion", () => {+++ it('keeps the deleted-session preview on the visible message projection', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'), 'utf8');+ const deletionBlock = source.slice(+ source.indexOf('export async function commitMessageDeletion'),+ source.indexOf('export function broadcastMessageDeleted'),+ );++ expect(deletionBlock).toContain('const latest = await latestVisiblePreviewRow(sessionId);');+ expect(deletionBlock).toContain(+ 'preview = extractMessagePreview(latest?.content, latest?.role);',+ );+ expect(deletionBlock).not.toContain('persistSessionListPreview(');+ expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');+ });+++ /**+ * issue #1282:删除路径一度用「可见 user/assistant 行数」去 patch `_count.messages`,而列表的+ * 权威口径是全部 messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL),差几十倍。shallow+ * merge 消费端不会自纠,错值留到下次 reseed。权威口径受删除影响只有 0 或 +1(见+ * commitMessageDeletion 的注释),不值得每次删除多跑一次全表 count,故整个字段不再广播。+ * 这几条静态断言守住「删除不按可见投影数行、不广播 _count」。+ */+ it('never patches _count.messages from the delete path', () => {+ const messagesSource = readFileSync(+ resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'),+ 'utf8',+ );+ const deletionStart = messagesSource.indexOf('export async function commitMessageDeletion');+ const deletionBlock = messagesSource.slice(+ deletionStart,+ messagesSource.indexOf('export function broadcastMessageDeleted'),+ );+ // 返回契约里不得再出现 messageCount——它就是 _count 广播的唯一来源。只看函数签名段,+ // 因为下方注释本身要提这个名字解释原因。(切点找不到时先失败在这里,否则 slice(-1) 会把+ // 整个文件当签名段,报出一个和真实原因无关的断言。)+ const bodyStart = messagesSource.indexOf('const now = Date.now()', deletionStart);+ expect(bodyStart).toBeGreaterThan(deletionStart);+ const signatureBlock = messagesSource.slice(deletionStart, bodyStart);+ expect(signatureBlock).not.toContain('messageCount');+ // 也不得再对可见投影数行。只匹配真实查询写法——注释里提 count 口径是允许的。+ expect(deletionBlock).not.toContain('.select({ messageCount');+ expect(deletionBlock).not.toMatch(/count\(messages\./);++ // 只切 broadcastSessionPatched 的对象字面量本身:整个 onCommitted 块里的注释也提 `_count`+ // (说明为什么不发),连注释一起断言会把自己打挂。+ const registerSource = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ const onCommittedStart = registerSource.indexOf('onCommitted:');+ expect(onCommittedStart).toBeGreaterThan(-1);+ const patchStart = registerSource.indexOf(+ 'broadcastSessionPatched(sessionId, {',+ onCommittedStart,+ );+ expect(patchStart).toBeGreaterThan(-1);+ const patchBlock = registerSource.slice(patchStart, registerSource.indexOf('});', patchStart));+ expect(patchBlock).toContain('preview,');+ expect(patchBlock).not.toContain('_count');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex c026c819c7..596f5b2346 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';import { performMessageDeletion, type MessageDeleteHandlerDeps } from '../messageDeleteHandler';@@ -59,67 +57,6 @@ describe('performMessageDeletion', () => {expect(vi.mocked(deps.commitDeletion).mock.calls[0]?.[2]).toContain('仍有效的承诺');});- it('keeps the deleted-session preview on the visible message projection', () => {- const source = readFileSync(resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'), 'utf8');- const deletionBlock = source.slice(- source.indexOf('export async function commitMessageDeletion'),- source.indexOf('export function broadcastMessageDeleted'),- );-- expect(deletionBlock).toContain('const latest = await latestVisiblePreviewRow(sessionId);');- expect(deletionBlock).toContain(- 'preview = extractMessagePreview(latest?.content, latest?.role);',- );- expect(deletionBlock).not.toContain('persistSessionListPreview(');- expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');- });-- /**- * issue #1282:删除路径一度用「可见 user/assistant 行数」去 patch `_count.messages`,而列表的- * 权威口径是全部 messages 行数(sessions.ts 的 SESSION_MESSAGE_COUNT_SQL),差几十倍。shallow- * merge 消费端不会自纠,错值留到下次 reseed。权威口径受删除影响只有 0 或 +1(见- * commitMessageDeletion 的注释),不值得每次删除多跑一次全表 count,故整个字段不再广播。- * 这几条静态断言守住「删除不按可见投影数行、不广播 _count」。- */- it('never patches _count.messages from the delete path', () => {- const messagesSource = readFileSync(- resolve(process.cwd(), 'src/main/localDb/ipc/messages.ts'),- 'utf8',- );- const deletionStart = messagesSource.indexOf('export async function commitMessageDeletion');- const deletionBlock = messagesSource.slice(- deletionStart,- messagesSource.indexOf('export function broadcastMessageDeleted'),- );- // 返回契约里不得再出现 messageCount——它就是 _count 广播的唯一来源。只看函数签名段,- // 因为下方注释本身要提这个名字解释原因。(切点找不到时先失败在这里,否则 slice(-1) 会把- // 整个文件当签名段,报出一个和真实原因无关的断言。)- const bodyStart = messagesSource.indexOf('const now = Date.now()', deletionStart);- expect(bodyStart).toBeGreaterThan(deletionStart);- const signatureBlock = messagesSource.slice(deletionStart, bodyStart);- expect(signatureBlock).not.toContain('messageCount');- // 也不得再对可见投影数行。只匹配真实查询写法——注释里提 count 口径是允许的。- expect(deletionBlock).not.toContain('.select({ messageCount');- expect(deletionBlock).not.toMatch(/count\(messages\./);-- // 只切 broadcastSessionPatched 的对象字面量本身:整个 onCommitted 块里的注释也提 `_count`- // (说明为什么不发),连注释一起断言会把自己打挂。- const registerSource = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),- 'utf8',- );- const onCommittedStart = registerSource.indexOf('onCommitted:');- expect(onCommittedStart).toBeGreaterThan(-1);- const patchStart = registerSource.indexOf(- 'broadcastSessionPatched(sessionId, {',- onCommittedStart,- );- expect(patchStart).toBeGreaterThan(-1);- const patchBlock = registerSource.slice(patchStart, registerSource.indexOf('});', patchStart));- expect(patchBlock).toContain('preview,');- expect(patchBlock).not.toContain('_count');- });-it('closes the old native session and rebuilds handoff from history without the target', async () => {const deps = makeDeps();diff --git a/apps/desktop/src/renderer/__tests__/aboutSocialLinks.test.ts b/apps/desktop/src/renderer/__tests__/aboutSocialLinks.test.tsindex f39009169c..62102ede2e 100644--- a/apps/desktop/src/renderer/__tests__/aboutSocialLinks.test.ts+++ b/apps/desktop/src/renderer/__tests__/aboutSocialLinks.test.ts@@ -1,15 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';--const aboutSource = readFileSync(- resolve(process.cwd(), 'src/renderer/components/settings/AboutSection.tsx'),- 'utf8',-);-const themeColorsSource = readFileSync(- resolve(process.cwd(), 'src/renderer/themes/colors.ts'),- 'utf8',-);const expectedXiaohongshuDescriptions: Record<string, string> = {'zh-CN': '关注中文内容','zh-TW': '關注中文內容',@@ -19,41 +10,6 @@ const expectedXiaohongshuDescriptions: Record<string, string> = {};describe('Settings About social links', () => {- it('uses the official destinations and prioritizes the Discord community', () => {- const discordIndex = aboutSource.indexOf('https://discord.gg/V4yKguac7K');- const xIndex = aboutSource.indexOf('https://x.com/making_cindy');- const xiaohongshuIndex = aboutSource.indexOf('https://xhslink.com/m/XmfveHjLlL');-- expect(discordIndex).toBeGreaterThan(-1);- expect(xIndex).toBeGreaterThan(discordIndex);- expect(xiaohongshuIndex).toBeGreaterThan(xIndex);- });-- it('renders a desktop three-column action card and opens links externally', () => {- expect(aboutSource).toContain('grid grid-cols-[repeat(auto-fit,minmax(240px,1fr))] gap-2.5');- expect(aboutSource).toContain(- 'min-h-[68px] min-w-0 select-none items-center gap-3 rounded-full px-6 py-2.5',- );- expect(aboutSource).toContain('window.electronAPI.openExternal(url)');- expect(aboutSource).toContain('if (!result.success)');- expect(aboutSource).toContain("toast.error(t('settings.about.social.openFailed'))");- expect(aboutSource).toContain('hover:bg-[var(--surface-hover)]');- expect(aboutSource).toContain('active:scale-[0.98]');- expect(aboutSource).toContain('active:bg-[var(--settings-social-card-pressed-bg)]');- expect(aboutSource).toContain(- 'transition-opacity duration-[var(--motion-fast,150ms)] group-hover:opacity-100',- );- expect(themeColorsSource).toContain("'settings-social-card-pressed-bg'");- expect(themeColorsSource).toContain(- 'color-mix(in srgb, var(--surface-hover) 88%, var(--text-primary) 12%)',- );- expect(aboutSource).toContain('focus-visible:ring-[var(--focus-ring-soft)]');- expect(aboutSource).not.toContain('aria-label={t(link.labelKey)}');- expect(aboutSource).toContain('{t(link.descriptionKey)}');- expect(aboutSource).toContain('fillRule="evenodd"');- expect(aboutSource).not.toContain('fill="var(--settings-theme-card-bg)"');- });-it.each(['zh-CN', 'zh-TW', 'en', 'ja', 'ko'])('provides social copy for %s', (locale) => {const messages = JSON.parse(readFileSync(diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.contract.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.contract.test.tsnew file mode 100644index 0000000000..322542f7fc--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/authContextRace.contract.test.ts@@ -0,0 +1,126 @@+// Guard tier: engineering-conventions section 3.2. Existing cross-file+// credential, permission, protocol, race, and design contracts are isolated+// from runtime unit tests. No new input or assertion is introduced here.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * Guards renderer auth state transitions. 产品 role 二段式水合已随 /api/me+ * 退役(2026-07):身份即 auth-server membership,不再有"迟到 role 响应"竞态,+ * 这里守住剩余的账号边界语义(切号清会话快照、迟到 initialize 丢弃)。+ */+describe('AuthContext auth-state races', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/renderer/contexts/AuthContext.tsx'),+ 'utf8',+ );+ const appSource = readFileSync(resolve(process.cwd(), 'src/renderer/App.tsx'), 'utf8');++ it('applies identity synchronously and resets session snapshot on account switch', () => {+ expect(source).toContain('activeDataOwnerIdRef.current !== state.dataOwnerId');+ expect(source).toContain('sessionsStore.reset();');+ expect(source).toContain('setUser(incoming);');+ // 防复活:renderer 不得再对业务 server 发起 role/资料水合请求。+ expect(source).not.toContain('meService');+ expect(source).not.toContain('apiRequest<');+ expect(source).not.toContain('getMe(');+ });++ it('repartitions every owner-scoped renderer store at the same boundary', () => {+ // 模型选择器持久轴(模型预设 / 引擎 override / 收藏副本)与 newMakerDraft 同待遇:+ // 同一处、同一个 state.dataOwnerId(登出快照里就是 null)。漏接任一个 = 多账号串号 ——+ // 这正是 providerModelMemory 不分账号踩过的坑,不能在新 store 上重演。+ const applyStart = source.indexOf('const applyIncomingState = useCallback');+ expect(applyStart).toBeGreaterThan(-1);+ const applyBlock = source.slice(applyStart, source.indexOf('[applyIncomingUser]', applyStart));+ for (const call of [+ 'setNewMakerDraftOwner(state.dataOwnerId);',+ 'setProviderModelMemoryOwner(state.dataOwnerId);',+ 'setModelEnginePrefsOwner(state.dataOwnerId);',+ 'setModelFavoritesOwner(state.dataOwnerId);',+ ]) {+ expect(applyBlock).toContain(call);+ }+ });++ it('applies the complete owner transition on local-mode boundaries', () => {+ // 本地模式进出同样是一次 dataOwnerId 切换。自己拼半套 setter 会漏草稿 /+ // prompt / 模型可见性 / 记忆分区(2026-08-21 #3201 Codex P1)。行为断言在+ // authContextSessionBoundary.test.tsx。+ for (const entry of ['const enterLocalMode = useCallback', 'const exitLocalMode = useCallback']) {+ const start = source.indexOf(entry);+ expect(start).toBeGreaterThan(-1);+ const block = source.slice(start, source.indexOf('[applyIncomingState, runDataOwnerBoundary]', start));+ expect(block).toContain('applyIncomingState(state);');+ expect(block).not.toContain('setModelEnginePrefsOwner(state.dataOwnerId);');+ }+ });++ it('ignores initialize results after a newer pushed auth event', () => {+ expect(source).toContain('authStateVersionRef.current += 1;');+ expect(source).toContain('authStateVersionRef.current !== initializeVersion');+ });++ it('clears login progress at auth boundaries', () => {+ expect(source).toContain('setLoginState(null);');+ expect(source).toContain('clearWorkersCache();');+ });++ it('publishes a data-owner generation at every auth boundary', () => {+ expect(source).toContain('cancelRemoteOptimisticSendsForDataOwnerBoundary();');+ expect(source).toContain('setDataOwnerGeneration(dataOwnerId, ownerGeneration);');+ expect(source).toContain('recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());');+ expect(source).toContain('invalidateProvidersSnapshot();');+ expect(source).toContain('publishDataOwnerGeneration(');+ expect(source).toContain('{ finalizeSessions: ownerBoundaryCommitted && !initialOwnerHydration }');+ expect(source).toContain(+ '// Invalidate in-flight remote sends before the confirmation dialog resolves.',+ );+ expect(source.match(/publishDataOwnerGeneration\(null\);/g)?.length).toBeGreaterThanOrEqual(2);+ expect(source.indexOf('cancelRemoteOptimisticSendsForDataOwnerBoundary();')).toBeLessThan(+ source.indexOf('setDataOwnerGeneration(dataOwnerId, ownerGeneration);'),+ );+ const enterLocal = source.indexOf('const enterLocalMode = useCallback');+ const exitLocal = source.indexOf('const exitLocalMode = useCallback');+ expect(source.indexOf('applyIncomingState(state);', enterLocal)).toBeLessThan(exitLocal);+ expect(source.indexOf('applyIncomingState(state);', exitLocal)).toBeGreaterThan(exitLocal);+ expect(source).toContain('activeDataOwnerGenerationRef.current');+ expect(source).toContain('setDataOwnerRecoveryEpoch((epoch) => epoch + 1);');+ expect(appSource).toContain("`${dataOwnerId ?? 'signed-out'}:${dataOwnerRecoveryEpoch}`");+ expect(appSource).toContain('<RouterProvider key={ownerKey} router={router} />');+ });++ it('projects browser waiting state before the main-process loopback request settles', () => {+ expect(source).toContain("if (action.type === 'start-browser')");+ expect(source).toContain("setLoginState({ step: 'browser-redirect', label: action.label });");+ });++ it('auto-continues a sole method-choice so fake pickers never paint', () => {+ expect(source).toContain('soleLoginMethod(result.state.methods)');+ expect(source).toContain("type: 'start-browser'");+ expect(source).toContain('providerOrConnectionId: sole.connectionId');+ expect(source).toContain("type: 'request-code'");+ expect(source).toContain("kind: 'email'");+ expect(source).toContain('identifier: result.state.email');+ const projectWaiting = source.indexOf(+ "setLoginState({ step: 'browser-redirect', label: action.label });",+ );+ const autoStart = source.indexOf('soleLoginMethod(result.state.methods)');+ expect(projectWaiting).toBeGreaterThan(-1);+ expect(autoStart).toBeGreaterThan(projectWaiting);+ });++ it('gates the sole-email auto request-code behind the login captcha gate', () => {+ // 唯一邮箱自动发码链不经过 LoginPage 的 dispatchRequestCode 闸;这里必须+ // 先问 loginCaptchaGate(global 开启 captcha 后,不过闸会不带 token 发码+ // 直接吃 400),取消(null)则停在 method-choice 不发码。+ expect(source).toContain("from '@/lib/loginCaptchaGate'");+ const gateAt = source.indexOf('getLoginEmailCaptchaGate()');+ const autoRequestAt = source.indexOf("type: 'request-code'");+ expect(gateAt).toBeGreaterThan(-1);+ expect(gateAt).toBeLessThan(autoRequestAt);+ expect(source).toContain('if (captchaToken === null)');+ expect(source).toContain('captchaToken,');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.test.tsindex f12255ab5a..3279570b37 100644--- a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { afterEach, describe, expect, it } from 'vitest';import {__testing as dataOwnerTesting,@@ -7,126 +5,6 @@ import {setDataOwnerGeneration,} from '@/contexts/dataOwnerGeneration';-/**- * Guards renderer auth state transitions. 产品 role 二段式水合已随 /api/me- * 退役(2026-07):身份即 auth-server membership,不再有"迟到 role 响应"竞态,- * 这里守住剩余的账号边界语义(切号清会话快照、迟到 initialize 丢弃)。- */-describe('AuthContext auth-state races', () => {- const source = readFileSync(- resolve(process.cwd(), 'src/renderer/contexts/AuthContext.tsx'),- 'utf8',- );- const appSource = readFileSync(resolve(process.cwd(), 'src/renderer/App.tsx'), 'utf8');-- it('applies identity synchronously and resets session snapshot on account switch', () => {- expect(source).toContain('activeDataOwnerIdRef.current !== state.dataOwnerId');- expect(source).toContain('sessionsStore.reset();');- expect(source).toContain('setUser(incoming);');- // 防复活:renderer 不得再对业务 server 发起 role/资料水合请求。- expect(source).not.toContain('meService');- expect(source).not.toContain('apiRequest<');- expect(source).not.toContain('getMe(');- });-- it('repartitions every owner-scoped renderer store at the same boundary', () => {- // 模型选择器持久轴(模型预设 / 引擎 override / 收藏副本)与 newMakerDraft 同待遇:- // 同一处、同一个 state.dataOwnerId(登出快照里就是 null)。漏接任一个 = 多账号串号 ——- // 这正是 providerModelMemory 不分账号踩过的坑,不能在新 store 上重演。- const applyStart = source.indexOf('const applyIncomingState = useCallback');- expect(applyStart).toBeGreaterThan(-1);- const applyBlock = source.slice(applyStart, source.indexOf('[applyIncomingUser]', applyStart));- for (const call of [- 'setNewMakerDraftOwner(state.dataOwnerId);',- 'setProviderModelMemoryOwner(state.dataOwnerId);',- 'setModelEnginePrefsOwner(state.dataOwnerId);',- 'setModelFavoritesOwner(state.dataOwnerId);',- ]) {- expect(applyBlock).toContain(call);- }- });-- it('applies the complete owner transition on local-mode boundaries', () => {- // 本地模式进出同样是一次 dataOwnerId 切换。自己拼半套 setter 会漏草稿 /- // prompt / 模型可见性 / 记忆分区(2026-08-21 #3201 Codex P1)。行为断言在- // authContextSessionBoundary.test.tsx。- for (const entry of ['const enterLocalMode = useCallback', 'const exitLocalMode = useCallback']) {- const start = source.indexOf(entry);- expect(start).toBeGreaterThan(-1);- const block = source.slice(start, source.indexOf('[applyIncomingState, runDataOwnerBoundary]', start));- expect(block).toContain('applyIncomingState(state);');- expect(block).not.toContain('setModelEnginePrefsOwner(state.dataOwnerId);');- }- });-- it('ignores initialize results after a newer pushed auth event', () => {- expect(source).toContain('authStateVersionRef.current += 1;');- expect(source).toContain('authStateVersionRef.current !== initializeVersion');- });-- it('clears login progress at auth boundaries', () => {- expect(source).toContain('setLoginState(null);');- expect(source).toContain('clearWorkersCache();');- });-- it('publishes a data-owner generation at every auth boundary', () => {- expect(source).toContain('cancelRemoteOptimisticSendsForDataOwnerBoundary();');- expect(source).toContain('setDataOwnerGeneration(dataOwnerId, ownerGeneration);');- expect(source).toContain('recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());');- expect(source).toContain('invalidateProvidersSnapshot();');- expect(source).toContain('publishDataOwnerGeneration(');- expect(source).toContain('{ finalizeSessions: ownerBoundaryCommitted && !initialOwnerHydration }');- expect(source).toContain(- '// Invalidate in-flight remote sends before the confirmation dialog resolves.',- );- expect(source.match(/publishDataOwnerGeneration\(null\);/g)?.length).toBeGreaterThanOrEqual(2);- expect(source.indexOf('cancelRemoteOptimisticSendsForDataOwnerBoundary();')).toBeLessThan(- source.indexOf('setDataOwnerGeneration(dataOwnerId, ownerGeneration);'),- );- const enterLocal = source.indexOf('const enterLocalMode = useCallback');- const exitLocal = source.indexOf('const exitLocalMode = useCallback');- expect(source.indexOf('applyIncomingState(state);', enterLocal)).toBeLessThan(exitLocal);- expect(source.indexOf('applyIncomingState(state);', exitLocal)).toBeGreaterThan(exitLocal);- expect(source).toContain('activeDataOwnerGenerationRef.current');- expect(source).toContain('setDataOwnerRecoveryEpoch((epoch) => epoch + 1);');- expect(appSource).toContain("`${dataOwnerId ?? 'signed-out'}:${dataOwnerRecoveryEpoch}`");- expect(appSource).toContain('<RouterProvider key={ownerKey} router={router} />');- });-- it('projects browser waiting state before the main-process loopback request settles', () => {- expect(source).toContain("if (action.type === 'start-browser')");- expect(source).toContain("setLoginState({ step: 'browser-redirect', label: action.label });");- });-- it('auto-continues a sole method-choice so fake pickers never paint', () => {- expect(source).toContain('soleLoginMethod(result.state.methods)');- expect(source).toContain("type: 'start-browser'");- expect(source).toContain('providerOrConnectionId: sole.connectionId');- expect(source).toContain("type: 'request-code'");- expect(source).toContain("kind: 'email'");- expect(source).toContain('identifier: result.state.email');- const projectWaiting = source.indexOf(- "setLoginState({ step: 'browser-redirect', label: action.label });",- );- const autoStart = source.indexOf('soleLoginMethod(result.state.methods)');- expect(projectWaiting).toBeGreaterThan(-1);- expect(autoStart).toBeGreaterThan(projectWaiting);- });-- it('gates the sole-email auto request-code behind the login captcha gate', () => {- // 唯一邮箱自动发码链不经过 LoginPage 的 dispatchRequestCode 闸;这里必须- // 先问 loginCaptchaGate(global 开启 captcha 后,不过闸会不带 token 发码- // 直接吃 400),取消(null)则停在 method-choice 不发码。- expect(source).toContain("from '@/lib/loginCaptchaGate'");- const gateAt = source.indexOf('getLoginEmailCaptchaGate()');- const autoRequestAt = source.indexOf("type: 'request-code'");- expect(gateAt).toBeGreaterThan(-1);- expect(gateAt).toBeLessThan(autoRequestAt);- expect(source).toContain('if (captchaToken === null)');- expect(source).toContain('captchaToken,');- });-});-describe('data-owner live push fencing', () => {afterEach(() => {dataOwnerTesting.reset();diff --git a/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts b/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.tsindex 329e614510..8eb6a9b4e5 100644--- a/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts+++ b/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts@@ -1,8 +1,6 @@// @vitest-environment jsdom-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { act, cleanup, render } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';import { createElement } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -14,15 +12,19 @@ import type { DeviceLinkSettings } from '@/hooks/useDeviceLinkSettings';import { MyDevicesPanel } from '@/components/settings/MyDevicesPanel';describe('MyDevicesPanel rename guards', () => {- it('does not write a manual name when rename is confirmed without changes', () => {- const source = readFileSync(- resolve(process.cwd(), 'src/renderer/components/settings/MyDevicesPanel.tsx'),- 'utf8',- );+ afterEach(cleanup);- expect(source).toContain('const currentName =');- expect(source).toContain('if (name && name === currentName) return;');- expect(source).toContain('await s.rename(deviceId, name || null);');+ it('does not write a manual name when rename is confirmed without changes', () => {+ const s = settings();+ render(createElement(MyDevicesPanel, { s, variant: 'self' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.devices.rename' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.devices.renameConfirm' }));+ expect(s.rename).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'settings.devices.rename' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Renamed Mac' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.devices.renameConfirm' }));+ expect(s.rename).toHaveBeenCalledExactlyOnceWith('self', 'Renamed Mac');});});diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.tsindex f6f35d15dd..e53abb5336 100644--- a/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts+++ b/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts@@ -1,6 +1,7 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { expect, it } from 'vitest';+import ts from 'typescript';// Guard tier (engineering-conventions §3.2): the long-lived sidebar owns the// worker notification subscription. Moving it into the conditional ExpandedView@@ -16,3 +17,29 @@ it('owns worker attention in the sidebar root across collapsed-view unmounts', (expect(source.slice(start, end)).toContain('useOrcaWorkerAttentionWatcher(sessionsHook.sessions, activeSessionId);');expect(source.slice(end)).not.toContain('useOrcaWorkerAttentionWatcher(');});++// Hidden/local/remote metadata must reach the root notification dispatcher.+it('passes unfiltered local and remote metadata to notification dispatch', () => {+ const filename = resolve(__dirname, '../features/cc-agent/CCAgentSidebarUpper.tsx');+ const source = ts.createSourceFile(filename, readFileSync(filename, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let rawRemote: string | undefined;+ const props = new Map<string, string>();+ function visit(node: ts.Node): void {+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === 'remoteProjectSessionsRaw' && !rawRemote) {+ rawRemote = node.initializer?.getText(source);+ }+ if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'ExpandedView') {+ for (const attribute of node.attributes.properties) {+ if (ts.isJsxAttribute(attribute) && attribute.initializer && ts.isJsxExpression(attribute.initializer)) {+ props.set(attribute.name.getText(source), attribute.initializer.expression?.getText(source) ?? '');+ }+ }+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+ expect(rawRemote).toContain('useSyncExternalStore');+ expect(rawRemote).toContain('remoteProjectsStore.getMergedRemoteSessions');+ expect(props.get('allSessionsForNotification')).toBe('allSessionsForAttentionRaw');+ expect(props.get('remoteSessionsForNotification')).toBe('remoteProjectSessionsRaw');+ });diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.contract.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.contract.test.tsnew file mode 100644index 0000000000..93d6e9906f--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.contract.test.ts@@ -0,0 +1,554 @@+// Guard tier (engineering-conventions section 3.2): cross-file capability,+// CAS/ack, owner-race, and model-selection interaction contracts cannot be+// isolated by importing the full composer tree. Behavioral transport, store,+// coordinator, and extracted callback tests stay in the unit tier.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';+++describe('ChatInput 的入口门控与调用路由', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const storeSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/lib/makerChatStore.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('切换 IPC 走传输层(远程会话隧道到被控端),不再硬打本机 maker', () => {+ expect(source).toContain('switchApi.switchSessionAgent(');+ expect(source).toContain(': makerApiFor(sourceSessionId);');+ expect(source).not.toContain('window.electronAPI.maker.switchSessionAgent(');+ });++ it('入口按被控端能力位门控:device-link 不再被排除,SSH 远程仍排除', () => {+ // 2026-08-12 统一模型选择器(M6):会话内换引擎有了两种形态,门禁必须**逐字一致** ——+ // · 统一面板(现在的常态):sessionEngineFilter 提供跨引擎入口;+ // · 旧两步分段(仅 device-link 老被控端 capabilities-only 降级时还会渲染):agentSwitch。+ // 任一处放松,SSH 远程或缺 CAS 能力的被控端就会露出一个必然失败的切换入口。+ expect(source).toContain(+ '!sessionId || !vendorKey || remoteHostId || !sessionAgentSwitchSupported',+ );+ expect(source).toMatch(+ /!unifiedPanelActive &&\s*\n\s*sessionId &&\s*\n\s*vendorKey &&\s*\n\s*!remoteHostId &&\s*\n\s*sessionAgentSwitchSupported/,+ );+ expect(source).toContain('hostCcCaps.capabilities?.supportsSessionAgentSwitch === true');+ expect(source).toContain('hostCcCaps.capabilities.supportsSessionAgentSwitchCas === true');+ expect(source).toContain('hostCodexCaps.capabilities?.supportsSessionAgentSwitch === true');+ expect(source).toContain('hostCodexCaps.capabilities.supportsSessionAgentSwitchCas === true');+ // 能力位读**任务所在的被控电脑**,不跟模型目录走(2026-10-09 review P1):Agent 在离线的+ // 第三台电脑时目录读不到,入口不能因此消失,否则改不回被控电脑。+ expect(source).toMatch(+ /const hostCcCaps = useAgentCapabilities\(\s*deviceLinkDeviceId \? 'claude-code' : null,\s*deviceLinkDeviceId \?\? undefined,\s*\);/,+ );+ expect(source).toMatch(+ /const hostCodexCaps = useAgentCapabilities\(\s*deviceLinkDeviceId \? 'codex' : null,\s*deviceLinkDeviceId \?\? undefined,\s*\);/,+ );+ expect(source).toContain(+ "hostCcCaps.capabilities?.supportsSessionAgentSwitchCas === true ||\n hostCodexCaps.capabilities?.supportsSessionAgentSwitchCas === true;",+ );+ const hostSource = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ expect(hostSource).toContain('supportsSessionAgentSwitchCas: true');+ });++ it('lazy-create 从 DB 对齐原子模型选择的 effort 与 Fast,不复用旧排队快照', () => {+ const hostSource = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ const start = hostSource.indexOf('async function reconcileCreateOptsAgainstDb(');+ const end = hostSource.indexOf('const agentSwitchDeps:', start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const body = hostSource.slice(start, end);+ expect(body).toContain('effort: sessions.effort,');+ expect(body).toContain('fastMode: sessions.fastMode,');+ expect(body).toContain('permissionMode: sessions.permissionMode,');+ expect(body).toContain("co.effort = (row.effort ?? undefined) as CreateOpts['effort'];");+ expect(body).toContain('co.fastMode = !!row.fastMode;');+ expect(body).toContain('co.permissionMode = permissionModeOrAsk(row.permissionMode);');+ });++ it('本地与远程会话打开时都读回 main 权威意图,并经新鲜度守卫过滤过期响应', () => {+ expect(source).toContain('if (!sessionId || remoteHostId) return;');+ expect(source).toContain('const switchApi = deviceLinkDeviceId');+ expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');+ expect(source).toContain(': makerApiFor(sessionId);');+ expect(source).toContain('.getSessionAgentSwitchIntent(sessionId)');+ expect(source).toContain('isAgentSwitchResponseFresh({');+ expect(source).toContain(+ 'makerChatStore.mirrorAgentSwitchIntent(sessionId, authoritativeIntent)',+ );+ // 每次点选都要推进写序号,外部变更靠 store 修订号 —— 少任一个 ABA 守卫都失效。+ expect(source).toContain('nextAgentSwitchWriteSeq(sourceSessionId)');+ expect(source).toContain('makerChatStore.getAgentSwitchIntentRev(sessionId)');+ // deviceId 跨重连不变,不把重连代际放进依赖就永远不会重试(断链期间的读回失败+ // 与错过的 sessions:patched 都靠这一跳补回)。+ expect(source).toContain(+ '}, [sessionId, deviceLinkDeviceId, remoteHostId, remoteReconnectEpoch]);',+ );+ expect(source).toContain("remoteConnStatus === 'connected'");+ });++ it('切换 ack 走分派决策:发起时捕获写序号与修订号,按分支判定而非一刀切 return', () => {+ expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');+ expect(source).toContain(+ 'const intentRevAtSend = makerChatStore.getAgentSwitchIntentRev(sourceSessionId);',+ );+ expect(source).toContain('const ackAction = resolveAgentSwitchAckAction({');+ // `return false` = 「这次选择没落地」(见「切换事务返回真实结果」一条)。+ expect(source).toContain("if (ackAction === 'discard') return false;");+ expect(source).toContain("if (ackAction === 'same-engine-reselect') {");+ expect(source).toContain('sameEngineRevision: result.sameEngineRevision,');+ expect(source).toContain('sameEngineSuperseded: result.sameEngineSuperseded,');+ });++ it('切换写入走模块级协调层(串行链与写序号按 session,不随组件卸载归零)', () => {+ expect(source).toContain('const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);');+ expect(source).toContain('await exclusiveTurn.ready;');+ expect(source).toContain('exclusiveTurn.release();');+ expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');+ expect(source).toContain('writeSeqNow: getAgentSwitchWriteSeq(sourceSessionId),');+ // 组件内不得再持有队列/序号 ref,否则重挂后又会分叉出第二条空队列。+ expect(source).not.toContain('agentSwitchWriteSeqRef');+ expect(source).not.toContain('agentSwitchQueueRef');++ const selectorSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ModelSelector.tsx'),+ 'utf8',+ );+ expect(selectorSource).not.toContain('agentSwitchQueueRef');+ expect(selectorSource).toContain(+ 'void agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);',+ );+ });++ it('同引擎重选与前置 invoke 共占一个串行位置,并在用最新 ref 前校验会话', () => {+ const reservation = source.indexOf(+ 'const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);',+ );+ const invoke = source.indexOf(+ // 带可选参数与不带参数的调用都必须在同一串行位置内完成。+ 'await switchApi.switchSessionAgent(',+ reservation,+ );+ const invokeWithoutOptions = source.indexOf('await switchApi.switchSessionAgent(', invoke + 1);+ const scopeGuard = source.indexOf(+ 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return false;',+ invoke,+ );+ const reselect = source.indexOf('const applied = providerId', scopeGuard);+ const staleGuard = source.indexOf('if (applied === false) return false;', reselect);+ const release = source.indexOf('exclusiveTurn.release();', reselect);+ expect(reservation).toBeGreaterThanOrEqual(0);+ expect(invoke).toBeGreaterThan(reservation);+ expect(invokeWithoutOptions).toBeGreaterThan(invoke);+ expect(scopeGuard).toBeGreaterThan(invokeWithoutOptions);+ expect(reselect).toBeGreaterThan(scopeGuard);+ expect(staleGuard).toBeGreaterThan(reselect);+ expect(release).toBeGreaterThan(reselect);+ });++ it('同引擎重选把 host 因果 token 带回 SET_MODEL,且遇到 superseded 不落后续状态', () => {+ expect(source).toContain('expectedAgentSwitchRevision?: number');+ expect(source).toContain('expectedAgentSwitchRevision === undefined &&');+ expect(source.split('expectedAgentSwitchRevision === undefined &&')).toHaveLength(3);+ expect(source).toContain('remoteAtomicModelSelectionSupported');+ expect(source).toContain(+ 'expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported',+ );+ expect(source).toContain('effort: newEffort,');+ expect(source).toContain('effort: targetEffort,');+ expect(source).toContain('fastMode: restoredFast,');+ expect(source).toContain('if (!useAtomicSelection) {');+ expect(source).toContain('if (remoteSetModelResult?.superseded) {');+ expect(source).not.toContain('if (!accepted || remoteSetModelResult?.superseded) {');+ expect(source).toContain('if (setModelResult?.superseded) {');+ expect(source).toContain('result.sameEngineRevision,');+ });++ it('切换意图登记完成前所有发送入口都被同步门禁,组件重挂后 pending 仍可见', () => {+ expect(source).toContain('const agentSwitchInFlight = useSyncExternalStore(');+ expect(source).toContain('const finishAgentSwitchOperation = beginAgentSwitchOperation(');+ expect(source).toContain('finishAgentSwitchOperation();');+ expect(source).toContain('? tryBeginAgentSendDispatch(sourceSessionId)');+ expect(source).toContain('agentSwitchInFlight ||');++ // composer 之外的继续 / 编辑重发等入口最终都经过共享 store 边界,不能要求每个+ // UI 调用点记得手工登记 token。+ const sendMessage = storeSource.indexOf('function sendMessage(');+ const sendMessageBegin = storeSource.indexOf('return withAgentSendDispatch(', sendMessage);+ const sendUiTrigger = storeSource.indexOf('function sendUiTrigger(');+ const uiTriggerBegin = storeSource.indexOf('return withAgentSendDispatch(', sendUiTrigger);+ const retryLastError = storeSource.indexOf('function retryLastError(');+ const retryBegin = storeSource.indexOf(+ 'return runAgentDispatchProjectionOperation(',+ retryLastError,+ );+ const compactSession = storeSource.indexOf('function compactSession(');+ const compactBegin = storeSource.indexOf(+ 'return runAgentDispatchProjectionOperation(',+ compactSession,+ );+ const resumeQueue = storeSource.indexOf('function resumeQueue(');+ const resumeBegin = storeSource.indexOf('runAgentDispatchProjectionOperation(', resumeQueue);+ const steerMessage = storeSource.indexOf('function steerMessage(');+ const steerBegin = storeSource.indexOf('return withAgentSendDispatch(', steerMessage);+ const steerQueuedMessage = storeSource.indexOf('function steerQueuedMessage(');+ const queuedSteerBegin = storeSource.indexOf(+ 'return withAgentSendDispatch(',+ steerQueuedMessage,+ );+ const resendBlockedMessage = storeSource.indexOf('async function resendBlockedMessage(');+ const blockedResendBegin = storeSource.indexOf(+ 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',+ resendBlockedMessage,+ );+ const sharedBegin = storeSource.indexOf(+ 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',+ );+ const sharedFinish = storeSource.indexOf(+ 'return task().finally(finishAgentSendDispatch);',+ sharedBegin,+ );+ expect(sendMessageBegin).toBeGreaterThan(sendMessage);+ expect(uiTriggerBegin).toBeGreaterThan(sendUiTrigger);+ expect(retryBegin).toBeGreaterThan(retryLastError);+ expect(compactBegin).toBeGreaterThan(compactSession);+ expect(resumeBegin).toBeGreaterThan(resumeQueue);+ expect(steerBegin).toBeGreaterThan(steerMessage);+ expect(queuedSteerBegin).toBeGreaterThan(steerQueuedMessage);+ expect(blockedResendBegin).toBeGreaterThan(resendBlockedMessage);+ expect(sharedBegin).toBeGreaterThanOrEqual(0);+ expect(sharedFinish).toBeGreaterThan(sharedBegin);+ });++ it('引用水合期间发送与切换双向互斥,并在真正发送前复核切换状态', () => {+ const sendBegin = source.indexOf('tryBeginAgentSendDispatch(sourceSessionId)');+ const hydrate = source.indexOf('await resolveSessionMessageReferencesForSend(editor);');+ const sendRecheck = source.indexOf(+ 'if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;',+ hydrate,+ );+ const onSend = source.indexOf('result = await onSend(', sendRecheck);+ const sendFinish = source.indexOf('finishAgentSendDispatch();', onSend);+ const sendSelfGuard = source.indexOf(+ 'if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;',+ );+ const switchGuard = source.indexOf(+ 'if (hasPendingAgentSendDispatch(sessionId)) return false;',+ sendFinish,+ );++ expect(sendSelfGuard).toBeGreaterThanOrEqual(0);+ expect(sendBegin).toBeGreaterThan(sendSelfGuard);+ expect(hydrate).toBeGreaterThan(sendBegin);+ expect(sendRecheck).toBeGreaterThan(hydrate);+ expect(onSend).toBeGreaterThan(sendRecheck);+ expect(sendFinish).toBeGreaterThan(onSend);+ expect(switchGuard).toBeGreaterThan(sendFinish);+ expect(source).toContain(+ 'disabled || settingsLocked || agentSendDispatchInFlight || agentSwitchInFlight',+ );+ });++ it('远程分支用稳定 deviceId 直连隧道:relay 瞬时重连会清空 sessionId→deviceId 索引', () => {+ expect(source).toContain('const switchApi = deviceLinkDeviceId');+ expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');+ expect(source).toContain(': makerApiFor(sourceSessionId);');+ });++ it('远程只切模型沿用当前 provider,避免 JSON optional 占位清除来源', () => {+ const start = source.indexOf('const performModelChange = useCallback(');+ const end = source.indexOf('const handleModelChange = useCallback(', start);+ const body = source.slice(start, end);+ expect(body).toMatch(+ /remoteMaker\.setModel\(\s*sessionId,\s*newModelId,\s*selectedProviderId,\s*expectedAgentSwitchRevision,/,+ );+ });++ it('await 返回后做会话作用域校验:旧会话响应不得借最新 ref 写进当前会话', () => {+ // `return false` 而不是裸 return:见下一条 —— 这是「没把选择落到会话上」的出口之一。+ expect(source).toContain(+ 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return false;',+ );+ // 读回同理:往返期间被切走就丢弃。+ expect(source).toContain(+ 'cancelled: cancelled || !isSessionScopeCurrent(sessionId, currentSessionIdRef.current),',+ );+ });++ /**+ * 2026-08-17 review 第二项:`performAgentSwitch` 必须把**真实结果**交出去。+ *+ * 病根:统一面板的跨引擎链路(`sessionEngineFilter.onCrossEngineSelect`)此前+ * fire-and-forget 之后立即 `return true` —— 那个 true 只表示「确认框过了」。面板侧把+ * 「成功才做」的清理挂在它上面(恢复推荐清 override / 删除当前选中的收藏),于是+ * `switchSessionAgent` 抛错、或 pending send 把切换挡下时,用户的 override / 收藏已经+ * 被清掉,原配置无从恢复。+ *+ * 锁三件事:① 所有「没落地」的出口返 false;② 登记 / 应用成功的出口返 true;+ * ③ 跨引擎回调 await 并原样透传,不再自己造布尔。+ */+ it('切换事务返回真实结果:失败 / 被拒返 false,登记成功才返 true', () => {+ const start = source.indexOf('const performAgentSwitch = useCallback(');+ expect(start).toBeGreaterThan(-1);+ const body = source.slice(+ start,+ source.indexOf('const performAgentSwitchRef = useRef(', start),+ );+ // 签名显式声明 Promise<boolean> —— 返回值是契约的一部分,不靠推断。+ expect(body).toContain('): Promise<boolean> => {');+ // 「没落地」的出口:无会话或设置只读 / pending send 拒绝 / 会话已切走 / ack 被超车。+ expect(body).toContain('if (!sessionId || settingsLocked) return false;');+ expect(body).toContain('if (hasPendingAgentSendDispatch(sessionId)) return false;');+ expect(body).toContain("if (ackAction === 'discard') return false;");+ // 同引擎重选被修订号守卫拒下 = 没落地。+ expect(body).toContain('if (applied === false) return false;');+ // 事务抛错(toast 之外)也必须让调用方知道「没切」。+ expect(body).toMatch(/\} catch \(err\) \{[\s\S]*?return false;\s*\} finally \{/);+ // 无条件 `return true;` 只剩同引擎重选成功 / 立即切换两条;apply-intent 的成功出口+ // 经完整配置一致性判据返回(2026-08-19 review P2 收口,见下一条锁)。+ expect(body.match(/return true;/g)?.length).toBe(2);+ // 登记成功 ≠ 完整配置落地:回声匹配路径的返回值必须过 effort / Fast 一致性判据 ——+ // 另一控制端在往返期间只改同一意图的档位 / Fast 时,本端请求没有原样落地,按 false+ // 上报,调用方挂在成功上的持久化收尾(onApplied 清 override / 提交・删除收藏编辑 /+ // 写收藏锚点)一律不做。+ expect(body).toContain('return isAgentSwitchEchoConfigConsistent({');+ expect(body).toContain('requestedEffort: newEffort,');+ expect(body).toContain('requestedFastMode: targetFast,');+ });++ it('统一面板的跨引擎回调 await 并透传事务结果,不再返回「确认框过了」', () => {+ const start = source.indexOf('const sessionEngineFilter = useMemo(');+ expect(start).toBeGreaterThan(-1);+ const body = source.slice(start, source.indexOf('}, [', start));+ // 取消确认 = false(现状,不变)。**有意变更**(Chris 2026-08-20):确认只认任务真实引擎,+ // 挂着的意图不算已经确认过 —— Claude 任务点了 Pi 收藏再点另一条,仍要弹框。+ expect(body).toContain('if (!(await confirmAgentBrowseSwitch(targetAgent))) return false;');+ expect(body).toContain('runtimeAgent: runtimeAgentKind ?? undefined,');+ // 真实结果原样交出去;绝不再出现 fire-and-forget + 提前 true。+ expect(body).toContain('const applied = await performAgentSwitchRef.current(');+ expect(body).toContain('return applied;');+ expect(body).not.toContain('void performAgentSwitchRef.current(');+ expect(body).not.toContain('return true;');+ // 收藏锚点也挂在**真实结果**上(2026-08-17 review 第三轮 G4):取消 / 失败不记锚点。+ expect(body).toContain('if (applied) {');+ expect(body).toContain('setSessionFavoriteAnchor(');+ });++ it('ack 判定带上「当前权威值就是本次登记那一份」,意图期改选一律 await 并透传结果', () => {+ // 1a:main 先广播 patched、后回 ack,push 必然先到并推走修订号 —— 缺这个判据,每一次+ // 正常登记都被自己的回声判成 stale(乐观呈现 / 草稿同步 / 收藏锚点全不落,而 main 的+ // 意图还在,下一条消息照样切引擎)。+ expect(source).toContain('registeredIntentMatchesCurrent,');+ expect(source).toContain('registeredIntent.target === targetAgentKind');+ expect(source).toContain('registeredIntent.model === newModelId');+ expect(source).toContain('registeredIntent.providerId === providerId');+ // providerId=null(跟随默认路由)时只认 target+model 的通配出口 —— main 可能把 null+ // 解析成具体来源再登记(2026-08-19 review P1 的前半)。+ expect(source).toContain('providerId === null ||');+ // ★ 回声已匹配时 apply-intent **整个跳过 note**(2026-08-19 两轮 P1 的合并收口):+ // store 里已是权威快照,任何本端旧值(null providerId / 旧 newEffort / 旧 targetFast)+ // 盖上去都会与被控端分叉 —— 覆盖「另一控制端只改 effort」「只改 Fast」「两者均改」+ // 与「main 归一化本端登记」全部场景;回声已到过,不会再有第二次权威回流纠正。+ expect(source).toContain('if (!registeredIntentMatchesCurrent) {');+ expect(source).not.toContain('appliedProviderId');+ // ★ 偏好同步同族(2026-08-19 review P2):回声已匹配时 syncSessionDraftModelPrefs 也必须+ // 用权威快照的 effort/fastMode/providerId —— 覆盖 effort-only / Fast-only / 两者均改 /+ // provider 归一化四种场景;权威快照缺某字段时该维不写,不回落本端旧值。+ expect(source).toContain(+ 'const authoritative = registeredIntentMatchesCurrent ? registeredIntent : null;',+ );+ expect(source).toContain(+ 'const syncedEffort = authoritative ? authoritative.effort : newEffort;',+ );+ expect(source).toContain(+ 'const syncedFast = authoritative ? authoritative.fastMode : targetFast;',+ );+ expect(source).toContain(+ 'const syncedProviderId = authoritative ? authoritative.providerId : providerId;',+ );+ expect(source).toContain('activeProviderId: syncedProviderId,');+ expect(source).toContain('memoryProviderId: syncedProviderId,');+ // (立即切换 apply-switched 分支仍可用本端值 —— 它以修订号未变为前提,没有已消费的+ // 权威回声,不在本锁范围内。)+ // 1d:意图期改选模型 / 来源必须 await 并把结果交回去,不能 fire-and-forget 返回+ // undefined 让上游读成「已应用」。+ expect(source).not.toContain('void performAgentSwitch(');+ expect(source).toContain(+ 'return await performAgentSwitch(intent.target, newModelId, null, {',+ );+ expect(source).toContain('intent.effort ? { effort: intent.effort as Effort }');+ // 意图期改选带来的 Fast override 必须过目标能力门,不能把旧 Fast 写进不支持的模型。+ expect(source).toContain('overrides.fastMode && fastCapable');+ });++ /**+ * Chris 2026-08-19「面板原地刷新」+ 2026-08-20「改思维闪关菜单」:+ * disabled 不得参与 popover 开关。`(open && !disabled) || keepOpen` 只保住确认框那条路,+ * 改思维走 performAgentSwitch 时 keepOpen 是 false,选单照关。+ */+ it('ModelSelector 的保命锁不被 disabled 压穿(两个 popover 分支同一表达式)', () => {+ const selectorSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ModelSelector.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const matches = selectorSource.match(/open=\{open \|\| keepOpenForAgentConfirmation\}/g) ?? [];+ expect(matches).toHaveLength(2);+ expect(selectorSource).not.toContain('(open || keepOpenForAgentConfirmation) && !disabled');+ expect(selectorSource).not.toContain('(open && !disabled) || keepOpenForAgentConfirmation');+ // 配置切引擎保持展开;选中模型行成功后收起。disabled 仍不得参与开关。+ expect(selectorSource).toContain('setOpenWithoutAutoRefresh(configuring || applied === false)');+ expect(selectorSource).toContain(+ "onProviderChange(args.providerId, args.wireModelId, args.effort ?? '', args.config.fast)",+ );+ });++ it('换引擎确认:回原引擎或点已确认的意图目标不再弹,换第三家仍要问', () => {+ expect(source).toContain('runtimeAgentKind === targetAgent');+ expect(source).toContain('agentSwitchIntent?.target === targetAgent');+ });++ it('会话传入历史收藏 uid,由统一面板校验完整配置后显示选中态', () => {+ expect(source).toContain('sessionFavoriteAnchor?.uid ?? null');+ expect(source).not.toContain('sessionFavoriteAnchor.wireModelId === activeModel');+ });++ it('跨引擎选中拿任务真实引擎比,不拿意图目标', () => {+ const actions = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/useUnifiedRowActions.ts'),+ 'utf8',+ );+ expect(actions).toContain('const runtimeAgent = sessionEngineFilter?.runtimeAgent;');+ expect(actions).not.toContain(+ 'const runtimeAgent = sessionEngineFilter?.runtimeAgent ?? sessionAgent;',+ );+ expect(actions).toContain('if (runtimeAgent === undefined) return true;');+ expect(actions).toContain('shouldCrossEngine(config.agent)');+ expect(actions).toContain('pendingSwitch');+ expect(actions).toContain('favoriteCopyIsLive');+ expect(actions).not.toContain('config.agent !== sessionAgent');+ });++ it('打开选单只滚动选中行,不把焦点从搜索框抢走', () => {+ const panel = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/UnifiedModelPanel.tsx'),+ 'utf8',+ );+ const ensure = panel.slice(+ panel.indexOf('const ensureSelectedVisible = useCallback'),+ panel.indexOf(' useEffect(() => {', panel.indexOf('const ensureSelectedVisible = useCallback')),+ );+ expect(ensure).not.toContain('row.focus');+ expect(ensure).toContain('computeSelectedRowScrollTop');+ });++ it('preserves Orca role and remote-worker provenance across the view and composer', () => {++ const remoteOptions = source.slice(source.indexOf('const sessionRemoteAgentOptions ='),+ source.indexOf('// composer pill 尾部引擎小标'));++ expect(source).not.toContain('sessionOrcaRole === null &&');++ expect(remoteOptions).toContain(' sessionOrcaRole,');++ expect(remoteOptions).toContain(' sessionOrcaRemoteWorker,');++ // 会话视图必须保留 undefined 未知态,避免在完整 session 回流前冒充具体身份。+ const viewSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),+ 'utf8',+ );++ expect(viewSource).toContain(+ 'sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}',+ );++ expect(viewSource).toContain('sessionOrcaRemoteWorker={!!session?.orcaRemoteLead}');+ });+});+++describe('CCAgentSessionView 上下文环压缩入口按 agent 能力分流(#1927)', () => {+ const viewSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('onCompact 门控:通道存在 + pi 排除 SSH 远程(remoteHostId) + pi running 禁用,codex 无通道不开放', () => {+ // 门控不再硬编码 agentKind 排除列表:以 compactChannel(能力判定)为准;+ // pi 的 SSH 远程会话(remoteHostId)无 compact-session 路由 → 显式排除+ // (与 SessionContentHeader 压缩菜单仅本地/device-link 一致,Copilot P2)。+ expect(viewSource).toContain('compactChannel !== null');+ expect(viewSource).toContain("!(realAgentKind === 'pi' && !!session?.remoteHostId)");+ // pi 回合运行中会拒绝压缩 → compact-session 通道 running 时禁用(与+ // SessionContentHeader 的 runningSessionIds 一致,codex P1);claude-input 保留旧行为。+ expect(viewSource).toContain(+ "!(compactChannel === 'compact-session' && agentStatus.isRunning)",+ );+ // codex(无 manualCompact)→ compactChannel null → 不开放(纯展示)。+ });++ it('compact-session 分支:粘滞路由 + 确认框后重新分流 + 失败反馈', () => {+ // 分流以当前 render 的 compactChannel 判定(channelNow),确认框返回后重新解析——+ // 同会话在其它窗口/远程被切换 agent 时捕获值会过期(codex P1)。+ expect(viewSource).toContain("if (channelNow === 'compact-session') {");+ // workingDir 只对 claude-input 是硬前提:compact-session(pi 原生压缩)不依赖它。+ expect(viewSource).toContain(+ "if (sourceCompactChannel === 'claude-input' && !sourceSession.workingDir) return;",+ );+ // device-link 远程 pi:粘滞归属路由到被控端,relay 重连窗口内不退回本机(greptile P1)。+ expect(viewSource).toContain('const sourceSessionId = sourceSession.id;');+ expect(viewSource).toContain('const maker = makerApiForSticky(sourceSessionId);');+ expect(viewSource).toContain('await maker.compactSession(sourceSessionId)');+ // 在途期间切换会话 / 登出 / 切回(换代):旧响应不得在当前视图弹 toast(并发收口)。+ expect(viewSource).toContain('const committedSessionId = sessionId ?? null;');+ expect(viewSource).toContain('compactRequestGuard.setCurrentSession(committedSessionId)');+ // 代校验:sessionId 当前 + 请求代一致;finally 里 release(不再按 sessionId finish)。+ expect(viewSource).toContain('const begun = compactRequestGuard.tryBegin(sourceSessionId);');+ expect(viewSource).toContain('if (!begun) return;');+ expect(viewSource).toContain('compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)');+ expect(viewSource).toContain('begun.release();');+ // 真实 reject 必须 catch 并显示 compactFailed。+ expect(viewSource).toContain("toast.warning(t('ccAgent.sidebar.sessionMenu.compactFailed'))");+ });++ it('claude-code 分支保持 inputCoordinator compactSession(model,...),不误入 compact-session', () => {+ // compact-session 分支以 return 结束;return 之前只有 makerApiForSticky 通道,+ // 不调用 inputCoordinator 的 compactSession(model, effort, ...)(即 maker:input:compact)。+ const csStart = viewSource.indexOf("if (channelNow === 'compact-session')");+ expect(csStart).toBeGreaterThan(-1); // 定位必须命中,否则断言形同虚设(copilot review)+ const csEnd = viewSource.indexOf('return;', csStart);+ const csBranch = viewSource.slice(csStart, csEnd);+ expect(csBranch).not.toContain('await compactSession(');+ // 确认框返回后若 channel 已消失(能力被撤/agent 切换)则放弃,不静默误调。+ // 关键:重分流必须读 compactChannelRef.current(useCallback 闭包固定捕获旧值,+ // 旧 async 函数 await 期间重新 render 也不会更新闭包——greptile review)。+ expect(viewSource).toContain('const compactChannelRef = useRef(compactChannel);');+ expect(viewSource).toContain('compactChannelRef.current = compactChannel;');+ expect(viewSource).toContain('const channelNow = compactChannelRef.current;');+ expect(viewSource).toContain('if (channelNow === null) return;');+ // claude 通道执行前才校验 workingDir(输入协调器硬前提),且参数必须来自**最新**+ // session 快照——同会话切换 agent 后 model/effort/permission/workingDir 已变化,+ // 旧快照会按错误配置执行(greptile P1 / codex P2)。+ expect(viewSource).toContain('const sessionRef = useRef(session);');+ expect(viewSource).toContain('sessionRef.current = session;');+ expect(viewSource).toContain('const sessionNow = sessionRef.current;');+ expect(viewSource).toContain("if (channelNow !== 'claude-input') return;");+ expect(viewSource).toContain('if (!sessionNow?.workingDir) return;');+ expect(viewSource).toContain('sessionNow.model,');+ // 确认框期间 turn 可能已从其它窗口/远程启动:render 时 isRunning 守卫失效,重读+ // 最新 running ref,活跃 turn 的 pi 拒绝压缩 → 放弃(codex P2);claude-input 保留旧行为。+ expect(viewSource).toContain('const isRunningRef = useRef(agentStatus.isRunning);');+ expect(viewSource).toContain('isRunningRef.current = agentStatus.isRunning;');+ expect(viewSource).toContain(+ "if (channelNow === 'compact-session' && isRunningRef.current) return;",+ );+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.tsindex 9602081566..9f44626758 100644--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts@@ -843,78 +843,15 @@ describe('makerChatStore 共享发送边界', () => {expect(coordinator.hasPendingAgentSendDispatch('compact-first')).toBe(false);});});--describe('ChatInput 的入口门控与调用路由', () => {+describe("ChatInput 的入口门控与调用路由", () => {const source = readFileSync(resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),'utf8',).replace(/\r\n/g, '\n');- const storeSource = readFileSync(- resolve(process.cwd(), 'src/renderer/lib/makerChatStore.ts'),- 'utf8',- ).replace(/\r\n/g, '\n');-- it('切换 IPC 走传输层(远程会话隧道到被控端),不再硬打本机 maker', () => {- expect(source).toContain('switchApi.switchSessionAgent(');- expect(source).toContain(': makerApiFor(sourceSessionId);');- expect(source).not.toContain('window.electronAPI.maker.switchSessionAgent(');- });-- it('入口按被控端能力位门控:device-link 不再被排除,SSH 远程仍排除', () => {- // 2026-08-12 统一模型选择器(M6):会话内换引擎有了两种形态,门禁必须**逐字一致** ——- // · 统一面板(现在的常态):sessionEngineFilter 提供跨引擎入口;- // · 旧两步分段(仅 device-link 老被控端 capabilities-only 降级时还会渲染):agentSwitch。- // 任一处放松,SSH 远程或缺 CAS 能力的被控端就会露出一个必然失败的切换入口。- expect(source).toContain(- '!sessionId || !vendorKey || remoteHostId || !sessionAgentSwitchSupported',- );- expect(source).toMatch(- /!unifiedPanelActive &&\s*\n\s*sessionId &&\s*\n\s*vendorKey &&\s*\n\s*!remoteHostId &&\s*\n\s*sessionAgentSwitchSupported/,- );- expect(source).toContain('hostCcCaps.capabilities?.supportsSessionAgentSwitch === true');- expect(source).toContain('hostCcCaps.capabilities.supportsSessionAgentSwitchCas === true');- expect(source).toContain('hostCodexCaps.capabilities?.supportsSessionAgentSwitch === true');- expect(source).toContain('hostCodexCaps.capabilities.supportsSessionAgentSwitchCas === true');- // 能力位读**任务所在的被控电脑**,不跟模型目录走(2026-10-09 review P1):Agent 在离线的- // 第三台电脑时目录读不到,入口不能因此消失,否则改不回被控电脑。- expect(source).toMatch(- /const hostCcCaps = useAgentCapabilities\(\s*deviceLinkDeviceId \? 'claude-code' : null,\s*deviceLinkDeviceId \?\? undefined,\s*\);/,- );- expect(source).toMatch(- /const hostCodexCaps = useAgentCapabilities\(\s*deviceLinkDeviceId \? 'codex' : null,\s*deviceLinkDeviceId \?\? undefined,\s*\);/,- );- expect(source).toContain(- "hostCcCaps.capabilities?.supportsSessionAgentSwitchCas === true ||\n hostCodexCaps.capabilities?.supportsSessionAgentSwitchCas === true;",- );- const hostSource = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),- 'utf8',- );- expect(hostSource).toContain('supportsSessionAgentSwitchCas: true');- });-- it('lazy-create 从 DB 对齐原子模型选择的 effort 与 Fast,不复用旧排队快照', () => {- const hostSource = readFileSync(- resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),- 'utf8',- );- const start = hostSource.indexOf('async function reconcileCreateOptsAgainstDb(');- const end = hostSource.indexOf('const agentSwitchDeps:', start);- expect(start).toBeGreaterThan(-1);- expect(end).toBeGreaterThan(start);- const body = hostSource.slice(start, end);- expect(body).toContain('effort: sessions.effort,');- expect(body).toContain('fastMode: sessions.fastMode,');- expect(body).toContain('permissionMode: sessions.permissionMode,');- expect(body).toContain("co.effort = (row.effort ?? undefined) as CreateOpts['effort'];");- expect(body).toContain('co.fastMode = !!row.fastMode;');- expect(body).toContain('co.permissionMode = permissionModeOrAsk(row.permissionMode);');- });it('Orca 会话复用切换入口,角色未加载仍保留未知态', () => {- expect(source).not.toContain('sessionOrcaRole === null &&');const expression = source.match(/const sessionAgentSwitchSupported =\s*([\s\S]*?);/)?.[1];- expect(expression).toBeDefined();+ if (!expression) throw new Error('Agent switch capability expression was not found');const supported = new Function('sessionOrcaRole', 'runtimeAgentKind', 'deviceLinkDeviceId','ccSupportsSessionAgentSwitch', 'codexSupportsSessionAgentSwitch', `return ${expression};`);for (const role of [null, 'lead', 'worker']) {@@ -926,10 +863,8 @@ describe('ChatInput 的入口门控与调用路由', () => {expect(supported(undefined, 'codex', null, true, true)).toBe(false);const remoteOptions = source.slice(source.indexOf('const sessionRemoteAgentOptions ='),source.indexOf('// composer pill 尾部引擎小标'));- expect(remoteOptions).toContain(' sessionOrcaRole,');- expect(remoteOptions).toContain(' sessionOrcaRemoteWorker,');const relocationGuard = remoteOptions.match(/if \(([\s\S]*?)\) return undefined;/)?.[1];- expect(relocationGuard).toBeDefined();+ if (!relocationGuard) throw new Error('Remote-agent relocation guard was not found');const hidden = new Function('sessionOrcaRole', 'sessionOrcaRemoteWorker', 'deviceLinkDeviceId',`const sessionId = 's1', agentLocationAware = true, remoteHostId = null, sessionEngineFilter = {};return !!(${relocationGuard});`);@@ -945,213 +880,6 @@ describe('ChatInput 的入口门控与调用路由', () => {expect(hidden(role, true, null)).toBe(true);}expect(hidden(undefined, false, null)).toBe(true);- // 会话视图必须保留 undefined 未知态,避免在完整 session 回流前冒充具体身份。- const viewSource = readFileSync(- resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),- 'utf8',- );- expect(viewSource).toContain(- 'sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}',- );- expect(viewSource).toContain('sessionOrcaRemoteWorker={!!session?.orcaRemoteLead}');- });-- it('本地与远程会话打开时都读回 main 权威意图,并经新鲜度守卫过滤过期响应', () => {- expect(source).toContain('if (!sessionId || remoteHostId) return;');- expect(source).toContain('const switchApi = deviceLinkDeviceId');- expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');- expect(source).toContain(': makerApiFor(sessionId);');- expect(source).toContain('.getSessionAgentSwitchIntent(sessionId)');- expect(source).toContain('isAgentSwitchResponseFresh({');- expect(source).toContain(- 'makerChatStore.mirrorAgentSwitchIntent(sessionId, authoritativeIntent)',- );- // 每次点选都要推进写序号,外部变更靠 store 修订号 —— 少任一个 ABA 守卫都失效。- expect(source).toContain('nextAgentSwitchWriteSeq(sourceSessionId)');- expect(source).toContain('makerChatStore.getAgentSwitchIntentRev(sessionId)');- // deviceId 跨重连不变,不把重连代际放进依赖就永远不会重试(断链期间的读回失败- // 与错过的 sessions:patched 都靠这一跳补回)。- expect(source).toContain(- '}, [sessionId, deviceLinkDeviceId, remoteHostId, remoteReconnectEpoch]);',- );- expect(source).toContain("remoteConnStatus === 'connected'");- });-- it('切换 ack 走分派决策:发起时捕获写序号与修订号,按分支判定而非一刀切 return', () => {- expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');- expect(source).toContain(- 'const intentRevAtSend = makerChatStore.getAgentSwitchIntentRev(sourceSessionId);',- );- expect(source).toContain('const ackAction = resolveAgentSwitchAckAction({');- // `return false` = 「这次选择没落地」(见「切换事务返回真实结果」一条)。- expect(source).toContain("if (ackAction === 'discard') return false;");- expect(source).toContain("if (ackAction === 'same-engine-reselect') {");- expect(source).toContain('sameEngineRevision: result.sameEngineRevision,');- expect(source).toContain('sameEngineSuperseded: result.sameEngineSuperseded,');- });-- it('切换写入走模块级协调层(串行链与写序号按 session,不随组件卸载归零)', () => {- expect(source).toContain('const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);');- expect(source).toContain('await exclusiveTurn.ready;');- expect(source).toContain('exclusiveTurn.release();');- expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');- expect(source).toContain('writeSeqNow: getAgentSwitchWriteSeq(sourceSessionId),');- // 组件内不得再持有队列/序号 ref,否则重挂后又会分叉出第二条空队列。- expect(source).not.toContain('agentSwitchWriteSeqRef');- expect(source).not.toContain('agentSwitchQueueRef');-- const selectorSource = readFileSync(- resolve(process.cwd(), 'src/renderer/components/new-chat/ModelSelector.tsx'),- 'utf8',- );- expect(selectorSource).not.toContain('agentSwitchQueueRef');- expect(selectorSource).toContain(- 'void agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);',- );- });-- it('同引擎重选与前置 invoke 共占一个串行位置,并在用最新 ref 前校验会话', () => {- const reservation = source.indexOf(- 'const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);',- );- const invoke = source.indexOf(- // 带可选参数与不带参数的调用都必须在同一串行位置内完成。- 'await switchApi.switchSessionAgent(',- reservation,- );- const invokeWithoutOptions = source.indexOf('await switchApi.switchSessionAgent(', invoke + 1);- const scopeGuard = source.indexOf(- 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return false;',- invoke,- );- const reselect = source.indexOf('const applied = providerId', scopeGuard);- const staleGuard = source.indexOf('if (applied === false) return false;', reselect);- const release = source.indexOf('exclusiveTurn.release();', reselect);- expect(reservation).toBeGreaterThanOrEqual(0);- expect(invoke).toBeGreaterThan(reservation);- expect(invokeWithoutOptions).toBeGreaterThan(invoke);- expect(scopeGuard).toBeGreaterThan(invokeWithoutOptions);- expect(reselect).toBeGreaterThan(scopeGuard);- expect(staleGuard).toBeGreaterThan(reselect);- expect(release).toBeGreaterThan(reselect);- });-- it('同引擎重选把 host 因果 token 带回 SET_MODEL,且遇到 superseded 不落后续状态', () => {- expect(source).toContain('expectedAgentSwitchRevision?: number');- expect(source).toContain('expectedAgentSwitchRevision === undefined &&');- expect(source.split('expectedAgentSwitchRevision === undefined &&')).toHaveLength(3);- expect(source).toContain('remoteAtomicModelSelectionSupported');- expect(source).toContain(- 'expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported',- );- expect(source).toContain('effort: newEffort,');- expect(source).toContain('effort: targetEffort,');- expect(source).toContain('fastMode: restoredFast,');- expect(source).toContain('if (!useAtomicSelection) {');- expect(source).toContain('if (remoteSetModelResult?.superseded) {');- expect(source).not.toContain('if (!accepted || remoteSetModelResult?.superseded) {');- expect(source).toContain('if (setModelResult?.superseded) {');- expect(source).toContain('result.sameEngineRevision,');- });-- it('切换意图登记完成前所有发送入口都被同步门禁,组件重挂后 pending 仍可见', () => {- expect(source).toContain('const agentSwitchInFlight = useSyncExternalStore(');- expect(source).toContain('const finishAgentSwitchOperation = beginAgentSwitchOperation(');- expect(source).toContain('finishAgentSwitchOperation();');- expect(source).toContain('? tryBeginAgentSendDispatch(sourceSessionId)');- expect(source).toContain('agentSwitchInFlight ||');-- // composer 之外的继续 / 编辑重发等入口最终都经过共享 store 边界,不能要求每个- // UI 调用点记得手工登记 token。- const sendMessage = storeSource.indexOf('function sendMessage(');- const sendMessageBegin = storeSource.indexOf('return withAgentSendDispatch(', sendMessage);- const sendUiTrigger = storeSource.indexOf('function sendUiTrigger(');- const uiTriggerBegin = storeSource.indexOf('return withAgentSendDispatch(', sendUiTrigger);- const retryLastError = storeSource.indexOf('function retryLastError(');- const retryBegin = storeSource.indexOf(- 'return runAgentDispatchProjectionOperation(',- retryLastError,- );- const compactSession = storeSource.indexOf('function compactSession(');- const compactBegin = storeSource.indexOf(- 'return runAgentDispatchProjectionOperation(',- compactSession,- );- const resumeQueue = storeSource.indexOf('function resumeQueue(');- const resumeBegin = storeSource.indexOf('runAgentDispatchProjectionOperation(', resumeQueue);- const steerMessage = storeSource.indexOf('function steerMessage(');- const steerBegin = storeSource.indexOf('return withAgentSendDispatch(', steerMessage);- const steerQueuedMessage = storeSource.indexOf('function steerQueuedMessage(');- const queuedSteerBegin = storeSource.indexOf(- 'return withAgentSendDispatch(',- steerQueuedMessage,- );- const resendBlockedMessage = storeSource.indexOf('async function resendBlockedMessage(');- const blockedResendBegin = storeSource.indexOf(- 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',- resendBlockedMessage,- );- const sharedBegin = storeSource.indexOf(- 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',- );- const sharedFinish = storeSource.indexOf(- 'return task().finally(finishAgentSendDispatch);',- sharedBegin,- );- expect(sendMessageBegin).toBeGreaterThan(sendMessage);- expect(uiTriggerBegin).toBeGreaterThan(sendUiTrigger);- expect(retryBegin).toBeGreaterThan(retryLastError);- expect(compactBegin).toBeGreaterThan(compactSession);- expect(resumeBegin).toBeGreaterThan(resumeQueue);- expect(steerBegin).toBeGreaterThan(steerMessage);- expect(queuedSteerBegin).toBeGreaterThan(steerQueuedMessage);- expect(blockedResendBegin).toBeGreaterThan(resendBlockedMessage);- expect(sharedBegin).toBeGreaterThanOrEqual(0);- expect(sharedFinish).toBeGreaterThan(sharedBegin);- });-- it('引用水合期间发送与切换双向互斥,并在真正发送前复核切换状态', () => {- const sendBegin = source.indexOf('tryBeginAgentSendDispatch(sourceSessionId)');- const hydrate = source.indexOf('await resolveSessionMessageReferencesForSend(editor);');- const sendRecheck = source.indexOf(- 'if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;',- hydrate,- );- const onSend = source.indexOf('result = await onSend(', sendRecheck);- const sendFinish = source.indexOf('finishAgentSendDispatch();', onSend);- const sendSelfGuard = source.indexOf(- 'if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;',- );- const switchGuard = source.indexOf(- 'if (hasPendingAgentSendDispatch(sessionId)) return false;',- sendFinish,- );-- expect(sendSelfGuard).toBeGreaterThanOrEqual(0);- expect(sendBegin).toBeGreaterThan(sendSelfGuard);- expect(hydrate).toBeGreaterThan(sendBegin);- expect(sendRecheck).toBeGreaterThan(hydrate);- expect(onSend).toBeGreaterThan(sendRecheck);- expect(sendFinish).toBeGreaterThan(onSend);- expect(switchGuard).toBeGreaterThan(sendFinish);- expect(source).toContain(- 'disabled || settingsLocked || agentSendDispatchInFlight || agentSwitchInFlight',- );- });-- it('远程分支用稳定 deviceId 直连隧道:relay 瞬时重连会清空 sessionId→deviceId 索引', () => {- expect(source).toContain('const switchApi = deviceLinkDeviceId');- expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');- expect(source).toContain(': makerApiFor(sourceSessionId);');- });-- it('远程只切模型沿用当前 provider,避免 JSON optional 占位清除来源', () => {- const start = source.indexOf('const performModelChange = useCallback(');- const end = source.indexOf('const handleModelChange = useCallback(', start);- const body = source.slice(start, end);- expect(body).toMatch(- /remoteMaker\.setModel\(\s*sessionId,\s*newModelId,\s*selectedProviderId,\s*expectedAgentSwitchRevision,/,- );});it.each(['lead', 'worker'])('Desktop Orca %s routes same-Agent model and provider picks through the switch intent', async sessionOrcaRole => {@@ -1171,7 +899,7 @@ describe('ChatInput 的入口门控与调用路由', () => {makerChatStore: { getAgentSwitchIntent: () => null }, performAgentSwitch: switchAgent,effectiveSourceId: 'provider-old', activeModel: 'model-old' };function callback(name: string) {- expect(callbacks.has(name)).toBe(true);+ if (!callbacks.has(name)) throw new Error(`Composer callback ${name} was not found`);const compiled = ts.transpileModule(`return ${callbacks.get(name)};`,{ compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;return new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));@@ -1183,261 +911,6 @@ describe('ChatInput 的入口门控与调用路由', () => {switchAgent.mockResolvedValue(false);expect(await callback('performModelChange')('rejected-model')).toBe(false);});-- it('await 返回后做会话作用域校验:旧会话响应不得借最新 ref 写进当前会话', () => {- // `return false` 而不是裸 return:见下一条 —— 这是「没把选择落到会话上」的出口之一。- expect(source).toContain(- 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return false;',- );- // 读回同理:往返期间被切走就丢弃。- expect(source).toContain(- 'cancelled: cancelled || !isSessionScopeCurrent(sessionId, currentSessionIdRef.current),',- );- });-- /**- * 2026-08-17 review 第二项:`performAgentSwitch` 必须把**真实结果**交出去。- *- * 病根:统一面板的跨引擎链路(`sessionEngineFilter.onCrossEngineSelect`)此前- * fire-and-forget 之后立即 `return true` —— 那个 true 只表示「确认框过了」。面板侧把- * 「成功才做」的清理挂在它上面(恢复推荐清 override / 删除当前选中的收藏),于是- * `switchSessionAgent` 抛错、或 pending send 把切换挡下时,用户的 override / 收藏已经- * 被清掉,原配置无从恢复。- *- * 锁三件事:① 所有「没落地」的出口返 false;② 登记 / 应用成功的出口返 true;- * ③ 跨引擎回调 await 并原样透传,不再自己造布尔。- */- it('切换事务返回真实结果:失败 / 被拒返 false,登记成功才返 true', () => {- const start = source.indexOf('const performAgentSwitch = useCallback(');- expect(start).toBeGreaterThan(-1);- const body = source.slice(- start,- source.indexOf('const performAgentSwitchRef = useRef(', start),- );- // 签名显式声明 Promise<boolean> —— 返回值是契约的一部分,不靠推断。- expect(body).toContain('): Promise<boolean> => {');- // 「没落地」的出口:无会话或设置只读 / pending send 拒绝 / 会话已切走 / ack 被超车。- expect(body).toContain('if (!sessionId || settingsLocked) return false;');- expect(body).toContain('if (hasPendingAgentSendDispatch(sessionId)) return false;');- expect(body).toContain("if (ackAction === 'discard') return false;");- // 同引擎重选被修订号守卫拒下 = 没落地。- expect(body).toContain('if (applied === false) return false;');- // 事务抛错(toast 之外)也必须让调用方知道「没切」。- expect(body).toMatch(/\} catch \(err\) \{[\s\S]*?return false;\s*\} finally \{/);- // 无条件 `return true;` 只剩同引擎重选成功 / 立即切换两条;apply-intent 的成功出口- // 经完整配置一致性判据返回(2026-08-19 review P2 收口,见下一条锁)。- expect(body.match(/return true;/g)?.length).toBe(2);- // 登记成功 ≠ 完整配置落地:回声匹配路径的返回值必须过 effort / Fast 一致性判据 ——- // 另一控制端在往返期间只改同一意图的档位 / Fast 时,本端请求没有原样落地,按 false- // 上报,调用方挂在成功上的持久化收尾(onApplied 清 override / 提交・删除收藏编辑 /- // 写收藏锚点)一律不做。- expect(body).toContain('return isAgentSwitchEchoConfigConsistent({');- expect(body).toContain('requestedEffort: newEffort,');- expect(body).toContain('requestedFastMode: targetFast,');- });-- it('统一面板的跨引擎回调 await 并透传事务结果,不再返回「确认框过了」', () => {- const start = source.indexOf('const sessionEngineFilter = useMemo(');- expect(start).toBeGreaterThan(-1);- const body = source.slice(start, source.indexOf('}, [', start));- // 取消确认 = false(现状,不变)。**有意变更**(Chris 2026-08-20):确认只认任务真实引擎,- // 挂着的意图不算已经确认过 —— Claude 任务点了 Pi 收藏再点另一条,仍要弹框。- expect(body).toContain('if (!(await confirmAgentBrowseSwitch(targetAgent))) return false;');- expect(body).toContain('runtimeAgent: runtimeAgentKind ?? undefined,');- // 真实结果原样交出去;绝不再出现 fire-and-forget + 提前 true。- expect(body).toContain('const applied = await performAgentSwitchRef.current(');- expect(body).toContain('return applied;');- expect(body).not.toContain('void performAgentSwitchRef.current(');- expect(body).not.toContain('return true;');- // 收藏锚点也挂在**真实结果**上(2026-08-17 review 第三轮 G4):取消 / 失败不记锚点。- expect(body).toContain('if (applied) {');- expect(body).toContain('setSessionFavoriteAnchor(');- });-- it('ack 判定带上「当前权威值就是本次登记那一份」,意图期改选一律 await 并透传结果', () => {- // 1a:main 先广播 patched、后回 ack,push 必然先到并推走修订号 —— 缺这个判据,每一次- // 正常登记都被自己的回声判成 stale(乐观呈现 / 草稿同步 / 收藏锚点全不落,而 main 的- // 意图还在,下一条消息照样切引擎)。- expect(source).toContain('registeredIntentMatchesCurrent,');- expect(source).toContain('registeredIntent.target === targetAgentKind');- expect(source).toContain('registeredIntent.model === newModelId');- expect(source).toContain('registeredIntent.providerId === providerId');- // providerId=null(跟随默认路由)时只认 target+model 的通配出口 —— main 可能把 null- // 解析成具体来源再登记(2026-08-19 review P1 的前半)。- expect(source).toContain('providerId === null ||');- // ★ 回声已匹配时 apply-intent **整个跳过 note**(2026-08-19 两轮 P1 的合并收口):- // store 里已是权威快照,任何本端旧值(null providerId / 旧 newEffort / 旧 targetFast)- // 盖上去都会与被控端分叉 —— 覆盖「另一控制端只改 effort」「只改 Fast」「两者均改」- // 与「main 归一化本端登记」全部场景;回声已到过,不会再有第二次权威回流纠正。- expect(source).toContain('if (!registeredIntentMatchesCurrent) {');- expect(source).not.toContain('appliedProviderId');- // ★ 偏好同步同族(2026-08-19 review P2):回声已匹配时 syncSessionDraftModelPrefs 也必须- // 用权威快照的 effort/fastMode/providerId —— 覆盖 effort-only / Fast-only / 两者均改 /- // provider 归一化四种场景;权威快照缺某字段时该维不写,不回落本端旧值。- expect(source).toContain(- 'const authoritative = registeredIntentMatchesCurrent ? registeredIntent : null;',- );- expect(source).toContain(- 'const syncedEffort = authoritative ? authoritative.effort : newEffort;',- );- expect(source).toContain(- 'const syncedFast = authoritative ? authoritative.fastMode : targetFast;',- );- expect(source).toContain(- 'const syncedProviderId = authoritative ? authoritative.providerId : providerId;',- );- expect(source).toContain('activeProviderId: syncedProviderId,');- expect(source).toContain('memoryProviderId: syncedProviderId,');- // (立即切换 apply-switched 分支仍可用本端值 —— 它以修订号未变为前提,没有已消费的- // 权威回声,不在本锁范围内。)- // 1d:意图期改选模型 / 来源必须 await 并把结果交回去,不能 fire-and-forget 返回- // undefined 让上游读成「已应用」。- expect(source).not.toContain('void performAgentSwitch(');- expect(source).toContain(- 'return await performAgentSwitch(intent.target, newModelId, null, {',- );- expect(source).toContain('intent.effort ? { effort: intent.effort as Effort }');- // 意图期改选带来的 Fast override 必须过目标能力门,不能把旧 Fast 写进不支持的模型。- expect(source).toContain('overrides.fastMode && fastCapable');- });-- /**- * Chris 2026-08-19「面板原地刷新」+ 2026-08-20「改思维闪关菜单」:- * disabled 不得参与 popover 开关。`(open && !disabled) || keepOpen` 只保住确认框那条路,- * 改思维走 performAgentSwitch 时 keepOpen 是 false,选单照关。- */- it('ModelSelector 的保命锁不被 disabled 压穿(两个 popover 分支同一表达式)', () => {- const selectorSource = readFileSync(- resolve(process.cwd(), 'src/renderer/components/new-chat/ModelSelector.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const matches = selectorSource.match(/open=\{open \|\| keepOpenForAgentConfirmation\}/g) ?? [];- expect(matches).toHaveLength(2);- expect(selectorSource).not.toContain('(open || keepOpenForAgentConfirmation) && !disabled');- expect(selectorSource).not.toContain('(open && !disabled) || keepOpenForAgentConfirmation');- // 配置切引擎保持展开;选中模型行成功后收起。disabled 仍不得参与开关。- expect(selectorSource).toContain('setOpenWithoutAutoRefresh(configuring || applied === false)');- expect(selectorSource).toContain(- "onProviderChange(args.providerId, args.wireModelId, args.effort ?? '', args.config.fast)",- );- });-- it('换引擎确认:回原引擎或点已确认的意图目标不再弹,换第三家仍要问', () => {- expect(source).toContain('runtimeAgentKind === targetAgent');- expect(source).toContain('agentSwitchIntent?.target === targetAgent');- });-- it('会话传入历史收藏 uid,由统一面板校验完整配置后显示选中态', () => {- expect(source).toContain('sessionFavoriteAnchor?.uid ?? null');- expect(source).not.toContain('sessionFavoriteAnchor.wireModelId === activeModel');- });-- it('跨引擎选中拿任务真实引擎比,不拿意图目标', () => {- const actions = readFileSync(- resolve(process.cwd(), 'src/renderer/components/new-chat/useUnifiedRowActions.ts'),- 'utf8',- );- expect(actions).toContain('const runtimeAgent = sessionEngineFilter?.runtimeAgent;');- expect(actions).not.toContain(- 'const runtimeAgent = sessionEngineFilter?.runtimeAgent ?? sessionAgent;',- );- expect(actions).toContain('if (runtimeAgent === undefined) return true;');- expect(actions).toContain('shouldCrossEngine(config.agent)');- expect(actions).toContain('pendingSwitch');- expect(actions).toContain('favoriteCopyIsLive');- expect(actions).not.toContain('config.agent !== sessionAgent');- });-- it('打开选单只滚动选中行,不把焦点从搜索框抢走', () => {- const panel = readFileSync(- resolve(process.cwd(), 'src/renderer/components/new-chat/UnifiedModelPanel.tsx'),- 'utf8',- );- const ensure = panel.slice(- panel.indexOf('const ensureSelectedVisible = useCallback'),- panel.indexOf(' useEffect(() => {', panel.indexOf('const ensureSelectedVisible = useCallback')),- );- expect(ensure).not.toContain('row.focus');- expect(ensure).toContain('computeSelectedRowScrollTop');- });-});--describe('CCAgentSessionView 上下文环压缩入口按 agent 能力分流(#1927)', () => {- const viewSource = readFileSync(- resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');-- it('onCompact 门控:通道存在 + pi 排除 SSH 远程(remoteHostId) + pi running 禁用,codex 无通道不开放', () => {- // 门控不再硬编码 agentKind 排除列表:以 compactChannel(能力判定)为准;- // pi 的 SSH 远程会话(remoteHostId)无 compact-session 路由 → 显式排除- // (与 SessionContentHeader 压缩菜单仅本地/device-link 一致,Copilot P2)。- expect(viewSource).toContain('compactChannel !== null');- expect(viewSource).toContain("!(realAgentKind === 'pi' && !!session?.remoteHostId)");- // pi 回合运行中会拒绝压缩 → compact-session 通道 running 时禁用(与- // SessionContentHeader 的 runningSessionIds 一致,codex P1);claude-input 保留旧行为。- expect(viewSource).toContain(- "!(compactChannel === 'compact-session' && agentStatus.isRunning)",- );- // codex(无 manualCompact)→ compactChannel null → 不开放(纯展示)。- });-- it('compact-session 分支:粘滞路由 + 确认框后重新分流 + 失败反馈', () => {- // 分流以当前 render 的 compactChannel 判定(channelNow),确认框返回后重新解析——- // 同会话在其它窗口/远程被切换 agent 时捕获值会过期(codex P1)。- expect(viewSource).toContain("if (channelNow === 'compact-session') {");- // workingDir 只对 claude-input 是硬前提:compact-session(pi 原生压缩)不依赖它。- expect(viewSource).toContain(- "if (sourceCompactChannel === 'claude-input' && !sourceSession.workingDir) return;",- );- // device-link 远程 pi:粘滞归属路由到被控端,relay 重连窗口内不退回本机(greptile P1)。- expect(viewSource).toContain('const sourceSessionId = sourceSession.id;');- expect(viewSource).toContain('const maker = makerApiForSticky(sourceSessionId);');- expect(viewSource).toContain('await maker.compactSession(sourceSessionId)');- // 在途期间切换会话 / 登出 / 切回(换代):旧响应不得在当前视图弹 toast(并发收口)。- expect(viewSource).toContain('const committedSessionId = sessionId ?? null;');- expect(viewSource).toContain('compactRequestGuard.setCurrentSession(committedSessionId)');- // 代校验:sessionId 当前 + 请求代一致;finally 里 release(不再按 sessionId finish)。- expect(viewSource).toContain('const begun = compactRequestGuard.tryBegin(sourceSessionId);');- expect(viewSource).toContain('if (!begun) return;');- expect(viewSource).toContain('compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)');- expect(viewSource).toContain('begun.release();');- // 真实 reject 必须 catch 并显示 compactFailed。- expect(viewSource).toContain("toast.warning(t('ccAgent.sidebar.sessionMenu.compactFailed'))");- });-- it('claude-code 分支保持 inputCoordinator compactSession(model,...),不误入 compact-session', () => {- // compact-session 分支以 return 结束;return 之前只有 makerApiForSticky 通道,- // 不调用 inputCoordinator 的 compactSession(model, effort, ...)(即 maker:input:compact)。- const csStart = viewSource.indexOf("if (channelNow === 'compact-session')");- expect(csStart).toBeGreaterThan(-1); // 定位必须命中,否则断言形同虚设(copilot review)- const csEnd = viewSource.indexOf('return;', csStart);- const csBranch = viewSource.slice(csStart, csEnd);- expect(csBranch).not.toContain('await compactSession(');- // 确认框返回后若 channel 已消失(能力被撤/agent 切换)则放弃,不静默误调。- // 关键:重分流必须读 compactChannelRef.current(useCallback 闭包固定捕获旧值,- // 旧 async 函数 await 期间重新 render 也不会更新闭包——greptile review)。- expect(viewSource).toContain('const compactChannelRef = useRef(compactChannel);');- expect(viewSource).toContain('compactChannelRef.current = compactChannel;');- expect(viewSource).toContain('const channelNow = compactChannelRef.current;');- expect(viewSource).toContain('if (channelNow === null) return;');- // claude 通道执行前才校验 workingDir(输入协调器硬前提),且参数必须来自**最新**- // session 快照——同会话切换 agent 后 model/effort/permission/workingDir 已变化,- // 旧快照会按错误配置执行(greptile P1 / codex P2)。- expect(viewSource).toContain('const sessionRef = useRef(session);');- expect(viewSource).toContain('sessionRef.current = session;');- expect(viewSource).toContain('const sessionNow = sessionRef.current;');- expect(viewSource).toContain("if (channelNow !== 'claude-input') return;");- expect(viewSource).toContain('if (!sessionNow?.workingDir) return;');- expect(viewSource).toContain('sessionNow.model,');- // 确认框期间 turn 可能已从其它窗口/远程启动:render 时 isRunning 守卫失效,重读- // 最新 running ref,活跃 turn 的 pi 拒绝压缩 → 放弃(codex P2);claude-input 保留旧行为。- expect(viewSource).toContain('const isRunningRef = useRef(agentStatus.isRunning);');- expect(viewSource).toContain('isRunningRef.current = agentStatus.isRunning;');- expect(viewSource).toContain(- "if (channelNow === 'compact-session' && isRunningRef.current) return;",- );- });});describe('上下文环压缩请求按 sessionId 隔离(#1927 并发/生命周期回归)', () => {diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.legalLinks.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.legalLinks.test.tsxindex 64e58953a2..7fa22393a9 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.legalLinks.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.legalLinks.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LEGAL_LINKS } from '../../../../shared/legalLinks';@@ -11,6 +11,7 @@ const toast = vi.hoisted(() => ({vi.mock('react-i18next', () => ({useTranslation: () => ({+ i18n: { language: 'en' },t: (key: string, options?: { document?: string }) =>options?.document ? `${key}:${options.document}` : key,}),@@ -20,7 +21,15 @@ vi.mock('@/lib/toast', () => ({toast,}));-import { LegalLinksRows } from '../AboutSection';+vi.mock('@/hooks/useAutoUpdateSettings', () => ({ useAutoUpdateSettings: () => ({ state: { loading: false } }) }));+vi.mock('@/hooks/useAnalyticsSettings', () => ({ useAnalyticsSettings: () => ({ state: { loading: false } }) }));+vi.mock('@/hooks/useLogUploadSettings', () => ({ useLogUploadSettings: () => ({ state: { loading: false } }) }));+vi.mock('@/hooks/useExperimentalFeatures', () => ({ useExperimentalFlag: () => ({ enabled: false, setEnabled: vi.fn() }) }));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: vi.fn() }) }));+vi.mock('@/components/log-support/LogSupportActions', () => ({ OpenLogsRow: () => null, UploadLogsRow: () => null }));+vi.mock('../PiKernelVersionRow', () => ({ PiKernelVersionRow: () => null }));++import { AboutSection, LegalLinksRows } from '../AboutSection';const openExternal = vi.fn();@@ -30,11 +39,35 @@ describe('AboutSection legal links', () => {openExternal.mockResolvedValue({ success: true });(window as unknown as { electronAPI: unknown }).electronAPI = {openExternal,+ maker: { agent: { getBinaryVersion: async () => ({ version: '1.0.0' }) } },};});afterEach(() => cleanup());+ // The old source checks never clicked a link or observed browser failures.+ // Reuse this component harness to verify the existing social actions.+ it('opens the displayed social destinations in community-first order', async () => {+ render(<AboutSection />);+ const panel = screen.getByRole('heading', { name: 'settings.about.social.title' }).parentElement!;+ const buttons = within(panel).getAllByRole('button');+ const destinations = ['https://discord.gg/V4yKguac7K', 'https://x.com/making_cindy', 'https://xhslink.com/m/XmfveHjLlL'];+ expect(buttons.map(button => button.title)).toEqual(destinations);+ for (const [index, button] of buttons.entries()) {+ fireEvent.click(button);+ await waitFor(() => expect(openExternal).toHaveBeenNthCalledWith(index + 1, destinations[index]));+ }+ expect(toast.error).not.toHaveBeenCalled();+ });++ it.each(['rejected', 'unsuccessful'])('shows the social failure message for a %s browser action', async mode => {+ if (mode === 'rejected') openExternal.mockRejectedValueOnce(new Error('Browser unavailable'));+ else openExternal.mockResolvedValueOnce({ success: false });+ render(<AboutSection />);+ fireEvent.click(screen.getByTitle('https://discord.gg/V4yKguac7K'));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('settings.about.social.openFailed'));+ });+it('renders both legal documents and opens the region-selected URLs externally', async () => {render(<LegalLinksRows />);diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.tsindex 089b8b81de..6647c5d773 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts@@ -123,27 +123,4 @@ describe('disabled Make notification dispatch', () => {await Promise.resolve();expect(send).toHaveBeenCalledWith('unknown', 'Unnamed task', 'error');});-- it('passes unfiltered local and remote metadata to notification dispatch', () => {- let rawRemote: string | undefined;- const props = new Map<string, string>();- function visit(node: ts.Node): void {- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === 'remoteProjectSessionsRaw' && !rawRemote) {- rawRemote = node.initializer?.getText(source);- }- if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'ExpandedView') {- for (const attribute of node.attributes.properties) {- if (ts.isJsxAttribute(attribute) && attribute.initializer && ts.isJsxExpression(attribute.initializer)) {- props.set(attribute.name.getText(source), attribute.initializer.expression?.getText(source) ?? '');- }- }- }- ts.forEachChild(node, visit);- }- visit(source);- expect(rawRemote).toContain('useSyncExternalStore');- expect(rawRemote).toContain('remoteProjectsStore.getMergedRemoteSessions');- expect(props.get('allSessionsForNotification')).toBe('allSessionsForAttentionRaw');- expect(props.get('remoteSessionsForNotification')).toBe('remoteProjectSessionsRaw');- });});diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsxindex da803eec8f..eed4422b42 100644--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { act, type ReactNode } from 'react';+import { act, useState, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { sharedTaskHostPeer } from '@cindy/device-link';@@ -71,6 +71,12 @@ function Harness({ companion = false, deviceId = 'd1' }: { companion?: boolean;const interactions = useSessionPendingInteractions('s1');return <InteractionPanel companion={companion} deviceId={deviceId} sessionId="s1" interactions={interactions} onError={onError} />;}+function CollapsibleHarness() {+ const interactions = useSessionPendingInteractions('s1');+ const [requestIds, setRequestIds] = useState<readonly string[]>([]);+ return <InteractionPanel deviceId="d1" sessionId="s1" interactions={interactions} onError={onError}+ collapse={{ requestIds, onToggle: (id) => setRequestIds((ids) => ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id]) }} />;+}beforeEach(() => {Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });vi.resetAllMocks();@@ -149,6 +155,30 @@ it.each(['plugin_setup', 'issue_confirm', 'ghost_grant_confirm', 'rename_sessionexpect(resolveInteraction).not.toHaveBeenCalled();});+// Bug #1493: collapse belongs to the caller and must survive a card being replaced.+it('collapses through the supplied intent, restores that intent after queue churn, and expands again', async () => {+ const ask = { request: { kind: 'ask_user_question', requestId: 'ask-collapse', questions: [{ question: 'Continue?' }] } };+ remoteSessionStore.setPendingInteractions('s1', [ask]);+ await act(async () => root.render(<CollapsibleHarness />));+ await click('interaction.panel.collapseButton');+ expect(host.querySelector('[data-testid="interaction.panel.collapsedBar"]')).not.toBeNull();+ expect(host.querySelector('[data-testid="interaction.ask.submitButton"]')).toBeNull();+ await act(async () => remoteSessionStore.setPendingInteractions('s1', [{ request: { kind: 'plugin_setup', requestId: 'setup-switch', revision: 1 } }]));+ expect(host.querySelector('[data-testid="interaction.panel.collapsedBar"]')).toBeNull();+ expect(host.querySelector('[data-testid="interaction.panel.collapseButton"]')).toBeNull();+ await act(async () => remoteSessionStore.setPendingInteractions('s1', [ask]));+ await click('interaction.panel.collapsedBar');+ expect(host.querySelector('[data-testid="interaction.ask.submitButton"]')).not.toBeNull();+});++// Remote kinds must not become i18next key paths. Observe the actual rendered title.+it.each(['permission.extra', '__proto__', 'constructor', 'unknown'])('normalizes remote kind %s to its translated fallback', async (kind) => {+ remoteSessionStore.setPendingInteractions('s1', [{ request: { kind, requestId: 'foreign-kind' } }]);+ await act(async () => root.render(<Harness />));+ expect(host.textContent).toContain('interaction.kinds.fallback.title');+ expect(host.textContent).not.toContain('interaction.kinds.' + kind + '.title');+});+it('keeps multiple selections and the free answer when moving back, remounting, and retrying', async () => {remoteSessionStore.setPendingInteractions('s1', [{ request: {kind: 'ask_user_question', requestId, questions: [diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.tsindex 0c4e3b3ea0..0e49e28d4a 100644--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts@@ -1,3 +1,4 @@+// guard: credentials-and-local-storage.md: restored credentials, account generations and realm activation must remain owned by the initiating account; static call-site contract.import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';@@ -256,3 +257,21 @@ describe('auth weak-network bootstrap', () => {expect(bootstrap).toContain('deleteSecureItem(LEGACY_USER_PROFILE_KEY)');});});++// guard: Credential owner generation: account rollback must re-register the restored identity.+describe("pushNotificationsRealm.test.ts call-site contracts", () => {+it('re-registers the restored owner after an account-switch rollback', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/notifications/PushNotificationsBridge.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const registrationStart = source.indexOf('// 登录态就绪后同步注册状态');+ const registrationBody = source.slice(+ registrationStart,+ source.indexOf('// APNs token 轮换', registrationStart),+ );++ expect(registrationBody).toContain('auth.accountGeneration');+ expect(registrationBody).toContain('syncPushRegistration(');+ });+});diff --git a/apps/mobile/src/__tests__/automationGroupPress.test.ts b/apps/mobile/src/__tests__/automationGroupPress.test.tsindex 1742b9ffc0..dbfc1ca814 100644--- a/apps/mobile/src/__tests__/automationGroupPress.test.ts+++ b/apps/mobile/src/__tests__/automationGroupPress.test.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';import { describe, expect, it, vi } from 'vitest';import type { RemoteSessionListItem } from '@cindy/maker-shared/session-list';import { resolveMobileSessionRowStatus } from '../session/sessionRightStatus';@@ -49,7 +50,22 @@ describe('automation group row press', () => {});it('keeps the arrow independent from row navigation', () => {- const arrow = source.slice(source.indexOf('event.stopPropagation();', start));- expect(arrow).toMatch(/^event.stopPropagation\(\);\s+onToggleAutomationGroup\?\.\(group.key\);/);+ const tree = ts.createSourceFile('HomeSurface.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let callback: ts.ArrowFunction | undefined;+ function visit(node: ts.Node) {+ if (ts.isArrowFunction(node) && node.parameters[0]?.name.getText(tree) === 'event'+ && node.body.getText(tree).includes('event.stopPropagation();')+ && node.body.getText(tree).includes('onToggleAutomationGroup')) callback = node;+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!callback) throw new Error('Missing production automation arrow callback');+ const onToggleAutomationGroup = vi.fn();+ const stopPropagation = vi.fn();+ const arrow = new Function('group', 'onToggleAutomationGroup', `return (${callback.getText(tree)});`)({ key: 'group' }, onToggleAutomationGroup);+ arrow({ stopPropagation });+ expect(stopPropagation).toHaveBeenCalledOnce();+ expect(onToggleAutomationGroup).toHaveBeenCalledExactlyOnceWith('group');+ expect(stopPropagation.mock.invocationCallOrder[0]).toBeLessThan(onToggleAutomationGroup.mock.invocationCallOrder[0]!);});});diff --git a/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts b/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.tsindex 2afd3da1cc..e90a775a11 100644--- a/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts+++ b/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts@@ -1,55 +1,101 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';--import { getDefaults } from 'react-i18next';-import { describe, expect, it } from 'vitest';-+import { act, createElement, memo, useCallback, useMemo, type ComponentType, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { getDefaults, useTranslation } from 'react-i18next';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { i18n } from '@/i18n';+import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';+import { mobileToolRowWording } from '@/i18n/toolWording';+import { summarizeToolRowPresentation, summarizeWorkGroupPresentation } from '@/session/messagePresentation';-/**- * 会话流里的工具行 / 工作组卡片按当前 app 语言解析文案。切语言时它们能刷新,- * 靠的是两件事:每个卡片自己持有 useTranslation 订阅(react-i18next 默认- * bindI18n='languageChanged' 会强制该组件重渲染,不受祖先 memo 影响),- * 以及各自 useMemo 依赖里带着 i18n.language。两条都用测试钉住。- */-const RENDERER = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');--function componentSource(name: string): string {- const start = RENDERER.indexOf(`function ${name}({`);- expect(start, `${name} 未找到`).toBeGreaterThan(-1);- const next = RENDERER.indexOf('\nfunction ', start + 1);- return RENDERER.slice(start, next === -1 ? undefined : next);+// Exercise the production hooks with a real languageChanged subscription and+// stable props. Importing the whole native message tree would mask these local+// subscriptions behind parent renders and require unrelated native view mocks.+const source = ts.createSourceFile('MessageRenderer.tsx', readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function component(name: string): ts.FunctionDeclaration | ts.FunctionExpression {+ let found: ts.FunctionDeclaration | ts.FunctionExpression | undefined;+ function visit(node: ts.Node) {+ if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name?.text === name) found = node;+ ts.forEachChild(node, visit);+ }+ visit(source);+ if (!found?.body) throw new Error('Message component was not found: ' + name);+ return found;+}+function statements(name: string, variables: string[]): string {+ return component(name).body!.statements.filter(statement => ts.isVariableStatement(statement)+ && statement.declarationList.declarations.some(declaration => variables.includes(declaration.name.getText(source))+ || declaration.initializer && ts.isCallExpression(declaration.initializer) && declaration.initializer.expression.getText(source) === 'useTranslation'))+ .map(statement => statement.getText(source)).join(String.fromCharCode(10));+}+function compile(code: string, bindings: Record<string, unknown>): ComponentType<Record<string, unknown>> {+ const emitted = ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React, jsxFactory: 'createElement' } }).outputText;+ return new Function(...Object.keys(bindings), emitted)(...Object.values(bindings));}+const bindings = { createElement, useTranslation, useMemo, useCallback, mobileToolRowWording, mobilePresentationLocalizer, summarizeToolRowPresentation, summarizeWorkGroupPresentation };+const cards = {+ ToolGroupCard: memo(compile('return function Harness({ actions, item, activity }) {' + statements('ToolGroupCard', ['rowOptions', 'toolRows']) + '; return createElement("output", null, JSON.stringify(toolRows)); };', bindings)),+ WorkGroupCard: memo(compile('return function Harness({ actions, item, activity }) {' + statements('WorkGroupCard', ['presentation']) + '; return createElement("output", null, JSON.stringify(presentation)); };', bindings)),+ WorkToolActivityRow: memo(compile('return function Harness({ actions, item, activity }) {' + statements('WorkToolActivityRow', ['tool', 'row']) + '; return createElement("output", null, JSON.stringify(row)); };', bindings)),+};-describe('会话流文案随 app 语言刷新', () => {- it('i18n init 未关闭 react-i18next 的 languageChanged 重渲染绑定', () => {- // options.react 未设置 → 用 react-i18next 默认值;默认值必须绑 languageChanged。+const tool = { key: 'tool', kind: 'tool', role: 'tool_use', label: 'Bash', body: '', align: 'agent', source: { toolName: 'Bash', toolInput: { command: 'printf hello' } } };+const item = { key: 'work', type: 'work_group', tools: [tool], children: [], isStreaming: true };+const activity = { key: 'activity', message: { normalized: tool }, status: 'running', intentOverride: undefined };+const props = { actions: { isSessionStreaming: false }, item, activity };+let root: Root;+let host: HTMLDivElement;+let previousLanguage: string;+beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ previousLanguage = i18n.language;+ await i18n.changeLanguage('en');+ host = document.createElement('div');+ root = createRoot(host);+});+afterEach(async () => {+ act(() => root.unmount());+ await i18n.changeLanguage(previousLanguage);+});++describe('message activity wording refreshes with app language', () => {+ it('keeps the default react-i18next languageChanged binding enabled', () => {expect(i18n.options.react).toBeUndefined();expect(getDefaults().bindI18n).toContain('languageChanged');});- it.each(['ToolGroupCard', 'WorkGroupCard', 'WorkToolActivityRow'])(- '%s 自己订阅 useTranslation 且 memo 依赖包含 i18n.language',- (name) => {- const source = componentSource(name);-- expect(source).toMatch(/useTranslation\(\)/);- expect(source).toContain('i18n.language');+ it.each(['ToolGroupCard', 'WorkGroupCard', 'WorkToolActivityRow'] as const)(+ '%s refreshes its cached presentation with no parent or prop change', async name => {+ await act(async () => root.render(createElement(cards[name], props)));+ const initial = host.textContent;+ expect(initial).toContain(name === 'WorkGroupCard' ? i18n.t('chat.workGroup.working') : mobileToolRowWording.verb('runCommand'));+ await act(async () => { await i18n.changeLanguage('zh-CN'); });+ expect(host.textContent).not.toBe(initial);+ expect(host.textContent).toContain(name === 'WorkGroupCard' ? i18n.t('chat.workGroup.working') : mobileToolRowWording.verb('runCommand'));},);- it('Markdown completed-block render callbacks invalidate translated fallback labels', () => {- const source = componentSource('MarkdownBody');- expect(source).toContain('const { t } = useTranslation()');- const inlineRenderer = source.slice(- source.indexOf('const renderInlines = useCallback('),- source.indexOf('const textRunGroupingOptions'),- );- expect(inlineRenderer).toMatch(/\[[^\]]*\bt\s*\],\s*\);\s*$/);- const runRenderer = source.slice(- source.indexOf('const renderTextRunBlock = useCallback('),- source.indexOf('const renderTextRun ='),- );- expect(runRenderer).toMatch(/\[[^\]]*\brenderInlines\b[^\]]*\]\);\s*$/);+ it('invalidates completed Markdown blocks when translated fallback labels change', async () => {+ const block = { type: 'paragraph', key: 'paragraph', inlines: [{ type: 'image', url: 'xdt-image://asset', alt: '' }] };+ const Text = ({ children }: { children?: ReactNode }) => createElement('span', null, children);+ const Block = memo(({ render }: { render: (block: unknown, leadingGap: boolean) => ReturnType<typeof createElement> }) => createElement('output', null, render(block, false)));+ const code = component('renderInline').getText(source) + '; return function Harness() {'+ + statements('MarkdownBody', ['renderInlines', 'renderTextRunBlock'])+ + '; return createElement(Block, { render: renderTextRunBlock }); };';+ const Markdown = compile(code, { ...bindings, Block, i18n, Text, MessageBodyText: Text,+ styles: {}, layout: { markdownBodyGap: 0 }, selectable: false, spanFor: () => undefined,+ onOpenSessionLink: undefined, openMarkdownImage: undefined, openMarkdownMedia: undefined,+ renderManagedImage: undefined, sessionLinkTitles: {}, streaming: false,+ isMobileMarkdownImageDirectUrl: () => false, clickableInlineStyle: () => undefined,+ });+ await act(async () => root.render(createElement(Markdown)));+ const initial = host.textContent;+ expect(initial).toBe(i18n.t('message.renderer.imageFallbackTitle'));+ await act(async () => { await i18n.changeLanguage('zh-CN'); });+ expect(host.textContent).not.toBe(initial);+ expect(host.textContent).toBe(i18n.t('message.renderer.imageFallbackTitle'));});});diff --git a/apps/mobile/src/__tests__/chatPathCandidate.test.ts b/apps/mobile/src/__tests__/chatPathCandidate.test.tsindex f9c6761345..b8ef6acb7a 100644--- a/apps/mobile/src/__tests__/chatPathCandidate.test.ts+++ b/apps/mobile/src/__tests__/chatPathCandidate.test.ts@@ -1,6 +1,73 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { join } from 'node:path';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import ts from 'typescript';++const rendererTree = ts.createSourceFile('renderer.tsx', readFileSync(join(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const pathFunctions = new Set(['ChatPathChipSpan', 'LinkPathChipSpan', 'clickableInlineStyle', 'underlineDecoration']);+const pathCode = rendererTree.statements.filter((node) => ts.isFunctionDeclaration(node) && node.name && pathFunctions.has(node.name.text)).map((node) => node.getText(rendererTree)).join('\n');+const compiledPath = ts.transpileModule(pathCode, { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+const flattenStyle = (value: any): any => Array.isArray(value) ? Object.assign({}, ...value.map(flattenStyle)) : value ?? {};+const pathContext = React.createContext<any>(null);+const verdictListeners = new Set<(key: string) => void>();+const verifyPath = vi.fn(async () => undefined);+const pathBindings = {+ React, useContext: React.useContext, useCallback: React.useCallback, useEffect: React.useEffect, useMemo: React.useMemo,+ useRecyclingState: React.useState, ChatFilePathContext: pathContext,+ resolveChatAbsPath, toWorkdirRel, canOpenChatPathChip, classifyChatPathLinkTarget, chatPathLabelReadsAsFileReference,+ StyleSheet: { flatten: flattenStyle },+ peekRemotePathVerdictForRender: () => 'unknown', peekRemotePathVerdict: () => undefined,+ remotePathVerdictKey: (device: string, workdir: string, path: string) => [device, workdir, path].join('|'),+ subscribeRemotePathVerdictChange: (listener: (key: string) => void) => { verdictListeners.add(listener); return () => verdictListeners.delete(listener); },+ verifyRemotePathCached: verifyPath,+};+const productionPath = new Function(...Object.keys(pathBindings), compiledPath + '\nreturn {ChatPathChipSpan, LinkPathChipSpan, clickableInlineStyle};')(...Object.values(pathBindings));+const pathStyles = { markdownLink: { textDecorationLine: 'underline' }, markdownPathChip: { textDecorationLine: 'underline' }, markdownInlineCode: { fontFamily: 'monospace' }, markdownUnderlineStrike: { textDecorationLine: 'underline line-through' } };++describe('production path spans', () => {+ it('adds the clickable signal only when a handler exists and preserves strike-through', () => {+ expect(flattenStyle(productionPath.clickableInlineStyle(pathStyles, undefined, {}))).toEqual({});+ expect(flattenStyle(productionPath.clickableInlineStyle(pathStyles, () => {}, {}))).toEqual({ textDecorationLine: 'underline' });+ expect(flattenStyle(productionPath.clickableInlineStyle(pathStyles, () => {}, { textDecorationLine: 'line-through' }))).toEqual({ textDecorationLine: 'underline line-through' });+ });++ // Bug #1144: cached verdict expiry must retry while the same span stays mounted.+ it('revalidates only its own cache key, preserves label shapes, and stops after unmount', async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ verifyPath.mockClear();+ const container = document.createElement('div');+ const root = createRoot(container);+ const open = vi.fn();+ const context = { deviceId: 'd1', workdir: '/repo', statPath: vi.fn(), onOpenPath: open };+ const SpanText = ({ children, style, onPress }: any) => React.createElement('span', { onClick: onPress, 'data-style': JSON.stringify(flattenStyle(style)) }, children);+ const render = (bare: boolean, display: string, streaming = false) => React.createElement(pathContext.Provider, { value: context },+ React.createElement(productionPath.LinkPathChipSpan, { url: 'src/a.ts', display, bare, styles: pathStyles, SpanText, baseStyle: {}, streaming }));+ try {+ await act(async () => root.render(render(true, 'src/a.ts')));+ expect(verifyPath).toHaveBeenCalledTimes(1);+ expect(container.firstElementChild?.getAttribute('data-style')).not.toContain('monospace');+ await act(async () => container.querySelector('span')!.click());+ expect(open).toHaveBeenCalledWith({ kind: 'file', absPath: '/repo/src/a.ts', relPath: 'src/a.ts' });+ await act(async () => { for (const listener of verdictListeners) listener('other-key'); });+ expect(verifyPath).toHaveBeenCalledTimes(1);+ await act(async () => { for (const listener of verdictListeners) listener('d1|/repo|/repo/src/a.ts'); });+ expect(verifyPath).toHaveBeenCalledTimes(2);+ await act(async () => root.render(render(false, 'a.ts')));+ expect(container.firstElementChild?.getAttribute('data-style')).toContain('monospace');+ await act(async () => root.render(render(false, 'Read the rules')));+ expect(container.firstElementChild?.getAttribute('data-style')).not.toContain('monospace');+ await act(async () => root.render(render(true, 'src/a.ts', true)));+ const calls = verifyPath.mock.calls.length;+ await act(async () => { for (const listener of verdictListeners) listener('d1|/repo|/repo/src/a.ts'); });+ expect(verifyPath).toHaveBeenCalledTimes(calls);+ } finally { await act(async () => root.unmount()); }+ expect(verdictListeners.size).toBe(0);+ });+});import {canOpenChatPathChip,@@ -365,19 +432,6 @@ describe('歧义候选的点亮门槛(DESIGN.md §14.5 规则 5)', () => {});});-describe('ambiguousShape 只能由单一判据产出(源码级守卫)', () => {- // 三个入口(行内 code / 显式链接 / 裸路径)历史上各自硬写过字面量,于是同一语义- // 在代码里有三份判据、改一处漏两处。收敛后只允许调 isAmbiguousChatPathShape。- it('chatPathCandidate.ts 里不出现 `ambiguousShape: true/false` 字面量', () => {- const src = readFileSync(- join(process.cwd(), 'src/session/chatPathCandidate.ts'),- 'utf8',- ).replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/[^\n]*/g, '$1');- expect(src, 'ambiguousShape 被硬写成字面量 —— 应统一走 isAmbiguousChatPathShape')- .not.toMatch(/ambiguousShape:\s*(true|false)\b/);- });-});-describe('chatPathLabelReadsAsFileReference(决定手写链接是否保留等宽 chip)', () => {// 桌面 shouldRenderCodeReferenceLabel 的移植,两端口径需同步。const c = (url: string) => {@@ -652,152 +706,3 @@ describe('findBareFilePathMatch(正文纯文本裸路径词法)', () => {expect(allValues('记作 a/b.c 即可')).toEqual(['a/b.c']);});});--describe('路径 chip 的可点信号(源码级守卫)', () => {- // DESIGN.md §14.5:可点与不可点的差异**只应是那条下划线**(对齐 GitHub ——- // `.markdown-body code` 不定义 color、纯靠继承,`.markdown-body a` 只加- // text-decoration、不加 font-weight)。RN 的样式合成没有类型保护,只能源码层钉。- const readRenderer = () =>- readFileSync(join(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- it('markdownPathChip 只有下划线:不改文字颜色、不改字重', () => {- const block = /markdownPathChip:\s*\{([^}]*)\}/.exec(readRenderer());- expect(block, '未找到 markdownPathChip 样式定义').not.toBeNull();- const body = block![1];- expect(body, '缺少下划线').toMatch(/textDecorationLine:\s*'underline'/);- // 可点的行内 code 必须与不可点的同色同字重 —— 多一个信号,「有横线 = 能点」- // 这条规则就少一分可信。- expect(body, '路径 chip 不得改文字颜色(应继承行内 code 的压暗档)').not.toMatch(/\bcolor:/);- expect(body, '路径 chip 不得改字重').not.toMatch(/fontWeight:/);- });-- it('markdownLink 只有正文色 + 下划线,不加粗', () => {- const block = /markdownLink:\s*\{([^}]*)\}/.exec(readRenderer());- expect(block, '未找到 markdownLink 样式定义').not.toBeNull();- const body = block![1];- expect(body).toMatch(/textDecorationLine:\s*'underline'/);- expect(body, '外链不得加粗(GitHub 的 a 也只有 text-decoration)').not.toMatch(/fontWeight:/);- });-- it('LinkPathChipSpan 的等宽 chip 是按来源 + label 条件套的,不是无条件开或关', () => {- const src = readRenderer();- const start = src.indexOf('function LinkPathChipSpan');- expect(start, '未找到 LinkPathChipSpan').toBeGreaterThan(-1);- const body = src.slice(start, start + 2400);- // 必须先按来源分流(bare = 正文裸写),再过 label 形态判定 —— 无条件去掉- // markdownInlineCode 会把作者手写的 `[README.md](path)` 一起降级成正文- // (PR #1144 review 实捉);无条件套上又会让裸路径点亮时形态跳变。- expect(body, '未按 bare 来源分流').toMatch(/!bare/);- expect(body, '未复用 label 形态判定').toContain('chatPathLabelReadsAsFileReference');- // 两个分支都在:套 chip 的与不套的。- expect(body, '缺少套等宽 chip 的分支').toMatch(/markdownInlineCode[\s\S]*markdownPathChip/);- expect(body, '缺少不套等宽的分支').toMatch(/\[baseStyle, underlineDecoration\(styles, baseStyle, styles\.markdownPathChip\)\]/);- });-- // ── 收敛检查点(PR #1144 两轮 review 各捉到一个「有下划线却点不动」) ──- // 不变量:**下划线 ⇔ 可点**,双向成立。根因是「加不加下划线」与「有没有 onPress」- // 在各分支独立决定 → 必然漂移。判据已收成 clickableInlineStyle 一处,这里钉住它- // 不被重新拆散。能区分错误修法:只修某一处 case 分支的写法过不了第一条。- it('markdownLink 只能经 clickableInlineStyle 取用,不得在 case 分支里直接写', () => {- const src = readRenderer();- const helperStart = src.indexOf('function clickableInlineStyle');- expect(helperStart, '未找到 clickableInlineStyle —— 判据被拆散了?').toBeGreaterThan(-1);- const helperEnd = src.indexOf('\n}', helperStart);- const helperBody = src.slice(helperStart, helperEnd);- // helper 自己必须按 onPress 决定下划线。- // 下划线经 underlineDecoration 叠加(外层删除线时合并成两条线),仍只在有 onPress 时出现。- expect(helperBody, 'helper 未按 onPress 分流').toMatch(- /onPress \? underlineDecoration\(styles, base, styles\.markdownLink\) : undefined/,- );- // 除 helper 自身外,全文件不应再出现 styles.markdownLink 的**用法**。- // 注释行(含 helper 的 JSDoc,它会引用这个名字来说明规则)不算用法。- const lines = src.split('\n');- const others = lines- .map((line, i) => ({ line, no: i + 1 }))- .filter(({ line }) => line.includes('styles.markdownLink'))- .filter(({ line }) => {- const t = line.trim();- return !t.startsWith('//') && !t.startsWith('*') && !t.startsWith('/*');- })- .filter(({ no }) => {- const at = lines.slice(0, no - 1).join('\n').length;- return at < helperStart || at > helperEnd;- });- expect(- others.map((o) => `${o.no}: ${o.line.trim()}`),- '有 case 分支绕过 clickableInlineStyle 直接用 markdownLink —— 会造出「有下划线却点不动」',- ).toEqual([]);- });-- // `~~链接~~` / `~~src/a.ts~~`:RN textDecorationLine 是单值,直接叠 underline 会盖掉外层- // line-through。可点下划线一律经 underlineDecoration,遇到删除线合并成两条线。- it('可点下划线经 underlineDecoration 叠加,外层删除线时合并为 underline line-through', () => {- const src = readRenderer();- const merged = /markdownUnderlineStrike:\s*\{([^}]*)\}/.exec(src);- expect(merged, '未找到 markdownUnderlineStrike 样式定义').not.toBeNull();- expect(merged![1]).toMatch(/textDecorationLine:\s*'underline line-through'/);- const helperStart = src.indexOf('function underlineDecoration');- expect(helperStart, '未找到 underlineDecoration').toBeGreaterThan(-1);- const helperBody = src.slice(helperStart, src.indexOf('\n}', helperStart));- expect(helperBody).toMatch(/textDecorationLine === 'line-through'/);- expect(helperBody).toContain('styles.markdownUnderlineStrike');- // markdownPathChip 的每处用法都经 underlineDecoration(样式定义行除外)。- const direct = src- .split('\n')- .filter((line) => line.includes('styles.markdownPathChip'))- .filter((line) => !line.includes('underlineDecoration(styles, baseStyle, styles.markdownPathChip)'));- expect(direct, '有路径 chip 绕过 underlineDecoration 直接叠下划线').toEqual([]);- });-- it('可点 inline 的 onPress 与样式取同一个值(不出现一边条件、一边无条件)', () => {- const src = readRenderer();- // 每个 clickableInlineStyle(styles, X, ...) 的 X 都必须同时是某处的 onPress={X}。- const handlers = [...src.matchAll(/clickableInlineStyle\(styles,\s*([A-Za-z_$][\w$]*)\s*[,)]/g)]- .map((m) => m[1]);- expect(handlers.length, '未找到 clickableInlineStyle 的调用').toBeGreaterThan(0);- for (const h of handlers) {- expect(src, `${h} 用作下划线判据却没有作为 onPress 传下去`).toContain(`onPress={${h}}`);- }- });-- it('行内 code 形态仍叠在 markdownInlineCode 之后(顺序错了下划线会被覆盖)', () => {- const src = readRenderer();- const sites = src.match(/chipStyle=\{\[[^\]]*\]\}/g) ?? [];- expect(sites.length).toBeGreaterThan(0);- for (const site of sites) {- const inline = site.indexOf('markdownInlineCode');- const chip = site.indexOf('markdownPathChip');- if (inline === -1 || chip === -1) continue;- expect(chip, `叠加顺序反了:${site}`).toBeGreaterThan(inline);- }- });-});--describe('远端 verdict 通知必须驱动重验,不能只驱动重绘(源码级守卫)', () => {- // 第 10 轮把点亮态改成缓存的纯派生时,桌面把 cacheGen 放进了验证副作用的依赖、- // 手机只在订阅回调里 setVerdict —— 而 readVerdict 是稳定的 useCallback,通知不改变- // 验证副作用的任何依赖,于是 TTL 到期后 chip 只完成「降级成纯文本」、没完成「重验」,- // 挂载期间永不自愈,比重构前(一直乐观点亮)更糟(PR #1144 review 实捉)。- //- // 这类 bug 的形状是「依赖数组漏了触发源」,没有类型保护、行为测试又要 RN 渲染,- // 所以在源码层钉住:通知必须递增计数,且计数必须出现在验证副作用的依赖里。- const src = readFileSync(join(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8')- .replace(/\/\*[\s\S]*?\*\//g, '')- .replace(/(^|[^:])\/\/[^\n]*/g, '$1');-- it('订阅回调递增计数(而不是只重绘)', () => {- const cb = /subscribeRemotePathVerdictChange\(\(key\) => \{([\s\S]*?)\}\);/.exec(src);- expect(cb, '未找到订阅回调').not.toBeNull();- expect(cb![1], '订阅回调只重绘、没驱动重验 —— TTL 到期后 chip 会降级且永不自愈')- .toMatch(/setCacheGen/);- });-- it('计数出现在验证副作用的依赖数组里', () => {- // 验证副作用的标志是它调用 verifyRemotePathCached;取其后最近的依赖数组。- const idx = src.indexOf('verifyRemotePathCached(');- expect(idx, '未找到验证副作用').toBeGreaterThan(-1);- const deps = /\}, \[([^\]]*)\]\);/.exec(src.slice(idx));- expect(deps, '未找到验证副作用的依赖数组').not.toBeNull();- expect(deps![1], 'cacheGen 不在依赖里 —— 缓存变化不会触发重验').toMatch(/cacheGen/);- });-});diff --git a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.tsindex 5d49f1a175..9abe4debe6 100644--- a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts+++ b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts@@ -55,3 +55,22 @@ describe('mobile cross-device quote wiring', () => {expect(source).toContain('item.quotesEncoded ? stripChatQuoteMarkerLines(item.text)');});});++// guard: message-source.md: persisted IM/source metadata must survive both renderer branches.+describe("hookSourceRendering.test.ts call-site contracts", () => {+it('downgrades only legacy hook rows (stored prompt) and keeps local IM rows as user rows', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');++ expect(source).toContain('&& !item.message.hookSource.userTextContent');+ expect(source).toContain("kind: 'system' as const, align: 'agent' as const");+ expect(source).toContain('testID="message.hookSource"');+ // 抬头走 i18n「Cindy · 来自 {{platform}}」,不再硬编码 Slack / Telegram / X。+ expect(source).toContain('{imSourceHeaderTitle(hookSource.im)}');+ expect(source).not.toContain("hookSource.im === 'x' ? 'X' : 'Slack'");+ expect(source).toContain('{hookSource.channelName}');+ // IM 卡片与桌面一样左对齐;长正文仍走有界测量与折叠保护。+ expect(source).toContain('presentation.isUserAligned && !item.message.hookSource');+ expect(source).toContain('(isUser || hookSource !== undefined)');+ expect(source).toContain("(item.message.kind === 'user' || hookSource !== undefined)");+ });+});diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.tsindex 4ae755d9ca..675b0368ad 100644--- a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts@@ -1,20 +1,58 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { runInNewContext } from 'node:vm';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import * as React from 'react';+import ts from 'typescript';+import { detectComposerTrigger } from '@/session/composerPalette';+import { replaceComposerTextRange, slashCommandTextNode, textComposerDocument } from '@/session/composerDocument';import { buildComposerRichInputHtml } from '@/session/composerRichInputHtml';import { parseComposerWebMessage } from '@/session/composerRichInputProtocol';+const pageTree = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function pageCallback(name: string, bindings: Record<string, unknown>) {+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(pageTree) === name) initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(pageTree);+ if (!initializer) throw new Error('Missing production composer callback ' + name);+ const expression = ts.isCallExpression(initializer) ? initializer.arguments[0] : initializer;+ const code = ts.transpileModule('const callback = ' + expression.getText(pageTree), { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+ return new Function(...Object.keys(bindings), code + '\nreturn callback;')(...Object.values(bindings));+}++it.each([false, true])('atomically applies a selected slash command while queue editing=%s', (editing) => {+ const apply = vi.fn(); const placeCaret = vi.fn(); const focus = vi.fn();+ const bindings = { pendingSkillSelectionRef: { current: null }, sessionId: 's1', draftRef: { current: '/he' },+ composerDocumentRef: { current: textComposerDocument('/he') }, queueEditingRef: { current: editing },+ composerInputRef: { current: { applyDocumentAndSetSelectionToEnd: placeCaret, focus } },+ applyComposerDocument: apply, detectComposerTrigger, replaceComposerTextRange, slashCommandTextNode };+ pageCallback('selectSlashCommand', bindings)({ name: 'help', kind: 'agent-skill' });+ const document = apply.mock.calls[0][0];+ expect(document.nodes).toEqual([{ type: 'text', text: '/help', slashCommand: '/help' }, { type: 'text', text: ' ' }]);+ expect(apply.mock.calls[0][1]).toEqual(editing ? { persist: false } : undefined);+ expect(placeCaret).toHaveBeenCalledExactlyOnceWith(document);+ expect(focus).not.toHaveBeenCalled();+ expect(bindings.pendingSkillSelectionRef.current).toEqual({ name: 'help', sid: 's1' });+});++it.each([false, true])('routes touch and accessibility activation through the actual dictation overlay (native=%s)', (nativeComposerAvailable) => {+ const finish = vi.fn();+ const press = pageCallback('handleComposerInputPressIn', { voiceRecordingActiveRef: { current: true }, voiceState: 'listening', finishVoiceRecordingRef: { current: finish } });+ const bindings = { React, voiceIsListening: true, nativeComposerAvailable, Pressable: 'Pressable', ScrollView: 'ScrollView', View: 'View', Text: 'Text', VoiceMicWaveCaret: 'Caret',+ t: (key: string) => key, styles: {}, handleComposerInputPressIn: press, voiceDraftScrollRef: {}, voiceDraftCaretFrame: { top: 0 },+ composerCardActive: true, composerInputScrollEnabled: false, voiceDraftShowsListeningPrompt: true, colors: { textPrimary: '#000' }, composerLayout: { input: { placeholder: 'Listening' } } };+ const overlay = pageCallback('renderComposerInputOverlay', bindings)();+ expect(overlay.props.accessibilityRole).toBe('button');+ overlay.props.onPress(); overlay.props.onPressIn();+ expect(finish).toHaveBeenNthCalledWith(1, { focusInput: true });+ expect(finish).toHaveBeenNthCalledWith(2, { focusInput: true });+ expect(pageCallback('renderComposerInputOverlay', { ...bindings, voiceIsListening: false })()).toBeNull();+});+describe('mobile composer rich input HTML', () => {- it('animates a native frame that fills the horizontal input row, preserving the WebView command ref', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');- const frame = source.slice(source.indexOf('frame: {'), source.indexOf('webView: {'));- expect(frame).toContain('flex: 1');- expect(frame).toContain('minWidth: 0');- expect(source).toContain('<Animated.View style={[styles.frame, heightStyle');- expect(source).not.toContain('createAnimatedComponent(WebView)');- expect(source).toContain('containerStyle={styles.webView}');- });const html = buildComposerRichInputHtml({accessibilityLabel: '输入消息',@@ -617,73 +655,6 @@ describe('mobile composer rich input HTML', () => {expect(html).not.toContain('"text":"<quoted>"');});- it('applies a selected slash command and its end-caret placement atomically', () => {- const inputSource = readFileSync(- resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const screenSource = readFileSync(- resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const selectStart = screenSource.indexOf('const selectSlashCommand = useCallback');- const selectEnd = screenSource.indexOf('const selectAtResource = useCallback', selectStart);- const selectSource = screenSource.slice(selectStart, selectEnd);-- expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;');- expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd: (value) => {');- expect(inputSource).toContain('applyDocument(value, true);');- expect(inputSource).toContain('if (pending) applyDocument(pending.document, pending.focusAfter, pending.caret);');- expect(inputSource).toContain('pendingNodeInsertionsRef.current.push(node);');- expect(inputSource).toContain('for (const node of pendingNodeInsertions)');- expect(selectSource).toContain('queueEditingRef.current ? { persist: false } : undefined');- expect(selectSource).toContain('composerInputRef.current?.applyDocumentAndSetSelectionToEnd(nextDocument);');- expect(selectSource).not.toContain('composerInputRef.current?.focus();');- });-- /**- * 「点输入区 = 想打字 → 停止听写」必须由听写期间盖在输入区上的 RN 覆盖层承接:- * - 挂 WebView 的 focus 不行:WKWebView 在输入区展开、拿到 native 焦点后会自己恢复- * DOM 焦点并派发 focus,收起态点语音、输入框展开的那一拍就把刚开始的听写掐断;- * - 挂 WebView 内的触摸也不行:听写期间富文本编辑器是 hidden(opacity 0),iOS hitTest- * 跳过 alpha≈0 的 view,它根本收不到触摸。- * 两条都由 2026-07 的实机日志确认。- */- it('stops dictation from the RN draft overlay instead of WebView focus', () => {- const screenSource = readFileSync(- resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const overlayStart = screenSource.indexOf('const renderComposerInputOverlay = ');- expect(screenSource.indexOf('// 听写期间只滚动覆盖层', overlayStart)).toBeGreaterThan(overlayStart);- const overlaySource = screenSource.slice(- overlayStart,- screenSource.indexOf('// 听写期间只滚动覆盖层', overlayStart),- );-- expect(overlaySource).toContain('onPressIn={handleComposerInputPressIn}');- // 无障碍激活(VoiceOver / TalkBack)只走 onPress,不会派发 onPressIn:两者都必须挂,- // 否则读屏用户按下这个「停止录音」按钮不会有任何反应。- expect(overlaySource).toContain('onPress={handleComposerInputPressIn}');- // Android 保留覆盖层的 44pt 命中区;iOS 使用常驻麦克风停止录音,- // 不再为了文字覆盖层额外抬高已展开的输入框。- expect(overlaySource).not.toContain('hitSlop');- expect(screenSource).toContain("inputFrameMinHeight={Platform.OS !== 'ios' && voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}");-- // hidden 的富文本编辑器必须同时从两端的无障碍树里摘掉:opacity: 0 不隐藏读屏焦点,- // 而它的 focus 已不再停听写,焦点留在那里会让读屏用户卡在「按了没反应」的输入框上。- const inputSource = readFileSync(- resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- expect(inputSource).toContain('accessibilityElementsHidden={hidden}');- expect(inputSource).toContain("importantForAccessibility={hidden ? 'no-hide-descendants' : 'auto'}");- expect(overlaySource).toContain('testID="session.voiceDraftOverlay"');- // 草稿滚动层本身不吃触摸,交给外层覆盖层。- expect(overlaySource).toContain('pointerEvents="none"');- expect(screenSource).toContain('onFocus={() => setComposerFocused(true)}');- });-it('rejects malformed image messages at the WebView boundary', () => {expect(parseComposerWebMessage(JSON.stringify({ type: 'paste-images-start', count: '2' }))).toBeNull();expect(parseComposerWebMessage(JSON.stringify({@@ -765,17 +736,4 @@ describe('mobile composer rich input HTML', () => {text: 42,}))).toBeNull();});-- it('falls back to the native clipboard when iOS omits paste clipboardData', () => {- const inputSource = readFileSync(- resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');-- expect(inputSource).toContain("import * as Clipboard from 'expo-clipboard';");- expect(inputSource).toContain('text = await Clipboard.getStringAsync();');- expect(inputSource).toContain('composerNodesForBoundedPlainTextPaste(text)');- expect(inputSource).toContain('window.cindyComposer.commitPaste(${JSON.stringify(message.requestId)}, []);');- expect(inputSource).toContain('window.cindyComposer.commitPaste(');- });});diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsxindex b59c54ead1..31dc5373c6 100644--- a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx@@ -260,6 +260,17 @@ it('settles interrupted paste placeholders and drops late clipboard results', asexpect(bridge.inject).not.toHaveBeenCalled();});+it.each(['text', 'empty', 'failure'])('settles a native clipboard fallback with %s', async (result) => {+ const { send, page } = mount();+ const commit = vi.fn();+ Object.assign(page, { commitPaste: commit });+ send({ type: 'ready' });+ if (result === 'failure') bridge.clipboard.mockRejectedValueOnce(new Error('clipboard unavailable'));+ else bridge.clipboard.mockResolvedValueOnce(result === 'text' ? 'pasted text' : '');+ await act(async () => send({ type: 'paste-text-request', requestId: 'clipboard' }));+ expect(commit).toHaveBeenCalledExactlyOnceWith('clipboard', result === 'text' ? [{ type: 'text', text: 'pasted text' }] : []);+});+it('retains structural endpoints when only a zero-width quote is selected', () => {const { ref, page, send } = mount();send({ type: 'ready' });diff --git a/apps/mobile/src/__tests__/composerSummaryLocaleRefresh.test.ts b/apps/mobile/src/__tests__/composerSummaryLocaleRefresh.test.tsindex 6f42c1be8e..5cbab70590 100644--- a/apps/mobile/src/__tests__/composerSummaryLocaleRefresh.test.ts+++ b/apps/mobile/src/__tests__/composerSummaryLocaleRefresh.test.ts@@ -1,26 +1,64 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { act, createElement, useMemo } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { useTranslation } from 'react-i18next';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { i18n } from '@/i18n';+import { effortLabelFromRuntime } from '@/session/modelPickerRows';-import { describe, expect, it } from 'vitest';+// Execute the real memo initializer and summary helpers. The old literal check+// could not observe a mounted summary retaining stale labels after locale changes.+function summaryMemo(file: string, name: string, helper: string) {+ const source = ts.createSourceFile(file, readFileSync(resolve(process.cwd(), file), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: string | undefined;+ const helpers: string[] = [];+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name) initializer = node.initializer?.getText(source);+ if (ts.isFunctionDeclaration(node) && [helper, 'choiceLabel'].includes(node.name?.text ?? '')) helpers.push(node.getText(source));+ ts.forEachChild(node, visit);+ }+ visit(source);+ if (!initializer || helpers.length !== 2) throw new Error('Runtime summary initializer or helper was not found: ' + name);+ const code = ts.transpileModule(helpers.join('\n') + '\nreturn ' + initializer + ';', {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ return new Function('useMemo', 'i18nInstance', 'effortLabelFromRuntime', 'composerDisplaySession', 'composerDisplayRuntimeOptions', 'draft', 'runtimeOptions', code);+}-/**- * composer / 新会话草稿摘要里的 effort 与权限标签按当前 app 语言解析,- * memo 依赖必须带上语言,否则切换语言后已挂载的路由会停在上一语言。- */-describe('composer 摘要随 app 语言重算', () => {- it('会话页 composerRuntimeSummary memo 依赖包含 i18n 语言', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- const memo = source.slice(source.indexOf('const composerRuntimeSummary = useMemo('));- const deps = memo.slice(memo.indexOf('['), memo.indexOf(']') + 1);-- expect(deps).toContain('i18nInstance.language');- });-- it('新建会话页 runtimeSummary memo 依赖包含 i18n 语言', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');- const memo = source.slice(source.indexOf('const runtimeSummary = useMemo('));- const deps = memo.slice(memo.indexOf('['), memo.indexOf(']') + 1);+const sessionSummary = summaryMemo('app/sessions/[sessionId].tsx', 'composerRuntimeSummary', 'buildComposerRuntimeSummary');+const draftSummary = summaryMemo('app/sessions/new.tsx', 'runtimeSummary', 'buildDraftRuntimeSummary');+let root: Root;+let host: HTMLDivElement;+let previousLanguage: string;+beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ previousLanguage = i18n.language;+ await i18n.changeLanguage('en');+ host = document.createElement('div');+ root = createRoot(host);+});+afterEach(async () => {+ act(() => root.unmount());+ await i18n.changeLanguage(previousLanguage);+});- expect(deps).toContain('i18nInstance.language');- });+describe('composer summaries refresh with app language', () => {+ it.each([['mounted task', sessionSummary], ['new task draft', draftSummary]] as const)(+ '%s recomputes labels without changing its task or runtime snapshot', async (_surface, summary) => {+ const task = { model: 'Luna', effort: 'xhigh', permissionMode: 'default' };+ const runtime = { currentModel: null, effortOptions: [{ id: 'xhigh', label: 'old snapshot' }], permissionOptions: [{ id: 'default', label: 'Default' }] };+ function Summary() {+ useTranslation();+ const value = summary(useMemo, i18n, effortLabelFromRuntime, task, runtime, task, runtime);+ return createElement('output', null, value.modelSummary);+ }+ await act(async () => root.render(createElement(Summary)));+ expect(host.textContent).toBe('Luna · Extra High');+ await act(async () => { await i18n.changeLanguage('zh-CN'); });+ expect(host.textContent).toBe('Luna · 超高');+ },+ );});diff --git a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.tsindex 7f0904596d..dc423dc5b3 100644--- a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts+++ b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts@@ -1,6 +1,7 @@import { readFileSync } from "node:fs";import { resolve } from "node:path";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";+import ts from "typescript";import {buildConversationShareHtml,@@ -51,6 +52,36 @@ function buildRichConversationHtml(): string {});}+it('bounds cleanup to old share PNGs while retaining recent successful files', async () => {+ const source = ts.createSourceFile('share.tsx', readFileSync(resolve(process.cwd(), 'src/session/ConversationShareWebView.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const declarations = source.statements.filter((node) => ts.isVariableStatement(node) && node.declarationList.declarations.some((item) => ['EXPORT_DIR_NAME', 'SHARE_PNG_RETAIN_COUNT', 'SHARE_PNG_CLEANUP_BATCH'].includes(item.name.getText(source))));+ const cleanup = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'cleanupConversationSharePngTemps');+ if (!cleanup) throw new Error('Missing production share cleanup');+ class File {+ extension = '.png'; exists = true; uri: string;+ constructor(public name: string, public modificationTime: number) { this.uri = 'file:///cache/conversation-share/' + name; }+ }+ const files = Array.from({ length: 16 }, (_, i) => new File('conversation-' + i + '.png', i));+ files.push(new File('unrelated.png', 30));+ const remove = vi.fn(async (_uri: string) => undefined);+ const Directory = class { exists = true; list() { return files; } };+ const code = ts.transpileModule(declarations.map((node) => node.getText(source)).join('\n') + '\n' + cleanup.getText(source).replace(/^export\s+/, ''), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const run = new Function('File', 'Directory', 'Paths', 'deleteConversationSharePngTemp', code + '\nreturn cleanupConversationSharePngTemps;')(File, Directory, { cache: 'cache' }, remove);+ await run();+ expect(remove.mock.calls.map((call) => call[0])).toEqual(files.slice(5, 13).reverse().map((file) => file.uri));+ expect(remove).toHaveBeenCalledTimes(8);+});++it('keeps approved footer output and a visible gap between non-adjacent selected messages', () => {+ const footer = buildRichConversationHtml();+ expect(footer).toContain('width: 22px;');+ expect(footer).toContain('height: 18px;');+ expect(footer).toContain('gap: 6px;');+ const html = buildConversationShareHtml({ allShareableIds: ['first', 'middle', 'third'], colors, contentWidth: 390,+ selectedMessages: [{ body: 'first', clientId: 'first', kind: 'user' }, { body: 'third', clientId: 'third', kind: 'assistant' }] });+ expect(html).toContain('<div class="share-gap" aria-hidden="true">⋯</div>');+});+describe("buildConversationShareHtml 富内容导出", () => {it.each([{ width: 390, height: 844, expectedWidth: 390 },@@ -310,240 +341,6 @@ describe("buildConversationShareHtml 富内容导出", () => {expect(html).not.toContain("https://example.com/image.png");});- it("限制原生与降级 renderer 的完整源尺寸,并安全保留已分享 PNG", () => {- const nativeSource = readFileSync(- resolve(- process.cwd(),- "modules/xdt-screenshot-monitor/ios/XdtScreenshotMonitorModule.swift",- ),- "utf8",- );- const webViewSource = readFileSync(- resolve(process.cwd(), "src/session/ConversationShareWebView.tsx"),- "utf8",- );- const sessionSource = readFileSync(- resolve(process.cwd(), "app/sessions/[sessionId].tsx"),- "utf8",- ).replace(/\r\n/g, "\n");-- expect(nativeSource).toContain("conversationShareMaxSourcePixels");- expect(nativeSource).toContain("UIWindow(windowScene: windowScene)");- expect(nativeSource).toContain(- "hostingWindow.rootViewController = viewController",- );- expect(nativeSource).toContain("hostingWindow?.isHidden = true");- expect(nativeSource).toContain("no active window scene");- expect(nativeSource).toContain("UIWindow.Level.normal.rawValue + 1");- expect(nativeSource).toContain("hostingWindow.alpha = 0.01");- expect(nativeSource).toContain("waitForWebContentPaint(webView)");- expect(nativeSource).toContain("requestAnimationFrame(resolve)");- expect(nativeSource).toContain("merged.hasVisibleVariation");- expect(nativeSource).toContain("Conversation share PNG is blank.");- expect(nativeSource).toContain("format.scale = 1");- expect(nativeSource).toContain(- "captureWidth * captureHeight <= conversationShareMaxSourcePixels",- );- expect(nativeSource).toContain(- "return numericValue.isFinite ? numericValue : nil",- );- expect(webViewSource).toContain(- "await deleteConversationSharePngTemp(file.uri);",- );- expect(webViewSource).toContain("SHARE_PNG_RETAIN_COUNT = 3");- expect(webViewSource).toContain("SHARE_PNG_CLEANUP_BATCH = 8");- expect(webViewSource).toContain(- "files.slice(SHARE_PNG_RETAIN_COUNT, SHARE_PNG_RETAIN_COUNT + SHARE_PNG_CLEANUP_BATCH)",- );- expect(sessionSource).toContain("deleteConversationSharePngTemp");- expect(sessionSource).toContain("cleanupConversationSharePngTemps");- expect(sessionSource).toContain("cache 目录交给下一次有界清理");- expect(sessionSource).toContain("if (!shareCompleted && localUri)");- expect(sessionSource).toContain("<ConversationShareSvg");- expect(sessionSource).toContain(- "nativeConversationShareAvailable = Platform.OS === 'ios'",- );- expect(sessionSource).toContain(- "if (!nativeConversationShareAvailable || !shareSelectionActive) return undefined;",- );- expect(sessionSource).toContain(- "const messages = await shareImages.prepare();",- );- expect(sessionSource).toContain(- "nativeConversationShareAvailable\n && shareCharacterSrc",- );- expect(sessionSource).toContain("renderConversationShareHtmlToPng({");- expect(sessionSource).toContain("nativeShareAssetsReady");- expect(sessionSource).toContain("native webview export succeeded");- expect(sessionSource).toContain("falling back to svg");- expect(sessionSource).not.toContain(- "OTA webview export failed; falling back to svg",- );- expect(sessionSource).toContain("return svg.exportPng();");- const shareAsyncIndex = sessionSource.indexOf(- "await sharing.shareAsync(localUri, { mimeType: 'image/png' });",- );- const shareCompletedIndex = sessionSource.indexOf(- "shareCompleted = true;",- shareAsyncIndex,- );- const postShareActiveCheckIndex = sessionSource.indexOf(- "if (!isShareOperationActive()) return;",- shareAsyncIndex,- );- expect(shareAsyncIndex).toBeGreaterThanOrEqual(0);- expect(shareCompletedIndex).toBeGreaterThan(shareAsyncIndex);- expect(shareCompletedIndex).toBeLessThan(postShareActiveCheckIndex);- });-- it("使用 Mobile 获批的克制页脚尺寸", () => {- const designSource = readFileSync(- resolve(process.cwd(), "../../docs/design-rules/DESIGN.md"),- "utf8",- );- const svgSource = readFileSync(- resolve(process.cwd(), "src/session/ConversationShareSvg.tsx"),- "utf8",- );- const html = buildRichConversationHtml();-- expect(designSource).toContain("Mobile approved 2026-08-08");- expect(designSource).toContain("src/session/ConversationShareSvg.tsx");- expect(designSource).toContain("22×22px (6px radius)");- expect(designSource).toContain("18px-high wordmark with a 6px gap");- expect(svgSource).toContain("const SHARE_CHARACTER_SIZE = 22;");- expect(svgSource).toContain("const SHARE_LOGO_HEIGHT = 18;");- expect(svgSource).toContain("const SHARE_LOCKUP_GAP = 6;");- expect(svgSource).toContain("rx={6}");- expect(svgSource).toContain("assetGate.waitUntilSettled()");- expect(svgSource).toContain('assetGate.markReady("character")');- expect(svgSource).toContain('assetGate.markReady("logo")');- expect(html).toContain("width: 22px;");- expect(html).toContain("height: 18px;");- expect(html).toContain("gap: 6px;");- });-- it("分享导出保持消息间距,并为隐藏 WebView 复用安全边界", () => {- const html = buildConversationShareHtml({- allShareableIds: ["first", "middle", "third"],- colors,- contentWidth: 390,- selectedMessages: [- { body: "first", clientId: "first", kind: "user" },- { body: "third", clientId: "third", kind: "assistant" },- ],- });- const webViewSource = readFileSync(- resolve(process.cwd(), "src/session/ConversationShareWebView.tsx"),- "utf8",- );- const shareBarSource = readFileSync(- resolve(process.cwd(), "src/session/ShareSelectionBar.tsx"),- "utf8",- );- const selectAllSource = readFileSync(- resolve(process.cwd(), "src/session/ShareSelectAllButton.tsx"),- "utf8",- );-- const messageCheckboxSource = readFileSync(- resolve(process.cwd(), "src/session/ShareMessageCheckbox.tsx"),- "utf8",- );- const messageRendererSource = readFileSync(- resolve(process.cwd(), "src/session/MessageRenderer.tsx"),- "utf8",- );- const sessionSource = readFileSync(- resolve(process.cwd(), "app/sessions/[sessionId].tsx"),- "utf8",- );-- expect(html).toContain('<div class="share-gap" aria-hidden="true">⋯</div>');- expect(html).toMatch(- /#xdt-content\.share-stage\s*\{[\s\S]*?display: flex;[\s\S]*?flex-direction: column;[\s\S]*?gap: 16px;/,- );- expect(shareBarSource).toContain("<HomeHeaderGlassButton");- const chromeStyle = readFileSync(- resolve(- process.cwd(),- "src/platform/chrome/nativeGlassButtonStyle.ios.ts",- ),- "utf8",- );- expect(chromeStyle).toContain("size = navigationChrome.target");- expect(chromeStyle).toContain(": { width: size, height: size })");- expect(shareBarSource).toContain("minHeight: 44,");- expect(shareBarSource).toContain("minWidth: 112,");- expect(shareBarSource).toContain("fontSize: typeScale.body,");- expect(selectAllSource).toContain("shareableIds.filter((clientId) =>");- expect(selectAllSource).toContain(- "selectionBeforeSelectAllRef.current?.includes(clientId)",- );- expect(selectAllSource).toContain(- "<ShareCheckboxMark checked={allSelected} />",- );- expect(selectAllSource).not.toContain(- "backgroundColor: colors.surfaceChip",- );- expect(messageCheckboxSource).toContain(- "onStartShouldSetResponder={() => !disabled}",- );- expect(messageCheckboxSource).toContain(- "onResponderTerminationRequest={() => true}",- );- expect(messageCheckboxSource).toContain("shouldCommitShareSelectionTap({");- expect(messageCheckboxSource).toContain(- "<ShareSelectionRowInteractionContext.Provider",- );- expect(messageCheckboxSource).toContain("if (!gesture.consumed) toggle();");- expect(messageCheckboxSource).not.toContain(- "fill ? styles.rowButton : styles.button",- );- expect(messageRendererSource).toContain(- "<View style={styles.shareSelectionContent}>",- );- expect(messageRendererSource).not.toContain(- 'pointerEvents="none" style={styles.shareSelectionContent}',- );- expect(messageRendererSource).toContain("useCancelShareSelectionRowTap()");- expect(messageRendererSource).toContain("fill");- expect(messageRendererSource).toContain(- 'testID="message.shareStickyCheck"',- );- expect(messageRendererSource).toContain(- "const shareableViews = Array.from(shareableMessageViewsRef.current.entries())",- );- expect(messageRendererSource).toContain(- "candidates.sort((a, b) => (a.frame?.y ?? Number.POSITIVE_INFINITY)",- );- expect(messageRendererSource).toContain(- "const pinned = candidates.find(({ frame }) => frame",- );- expect(messageRendererSource).toContain(- "frame.y + frame.height > dockY + SHARE_STICKY_CHECK_HEIGHT",- );- expect(messageRendererSource).toContain('pointerEvents="box-none"');- expect(messageRendererSource).toContain(- "marginLeft: wideContentInset + spacing.lg",- );- expect(messageRendererSource).not.toContain("styles.stickyShareSpacer");- expect(sessionSource).toContain(- "shareSelectionLeadingInset={nativeShellLayout.wideViewport",- );- expect(sessionSource).toContain(- "{ paddingLeft: shareSelectionLeadingInset + spacing.sm }",- );- expect(webViewSource).toContain(- "onShouldStartLoadWithRequest={interceptNavigation}",- );- expect(webViewSource).toContain(- "interceptHtmlNavigation(request, documentSettledRef.current)",- );- expect(webViewSource).toContain("allowFileAccess={false}");- expect(webViewSource).toContain('mediaCapturePermissionGrantType="deny"');- });-it("导出结构化正文和附件时保留可见投影,不泄露隐藏引用或外链", () => {const html = buildConversationShareHtml({allShareableIds: ["message"],diff --git a/apps/mobile/src/__tests__/devCacheMenu.test.ts b/apps/mobile/src/__tests__/devCacheMenu.test.tsindex 841958a63a..1cdfb0f9b4 100644--- a/apps/mobile/src/__tests__/devCacheMenu.test.ts+++ b/apps/mobile/src/__tests__/devCacheMenu.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// mobile vitest 跑在 node 环境(无 react-native / 无 __DEV__):mock 掉 react-native 的 DevSettings + 两层 cache 清理,@@ -66,14 +64,3 @@ describe('registerDevCacheMenu (dev-only debug entry — runtime gate)', () => {expect(reload).toHaveBeenCalledTimes(1);});});--describe('dev cache menu wiring (source assertions)', () => {- it('keeps the strict __DEV__ gate in source and is registered from RootLayout', () => {- const source = readFileSync(resolve(process.cwd(), 'src/debug/devCacheMenu.ts'), 'utf8');- expect(source).toContain('if (!__DEV__) return;');- expect(source).not.toContain('console.log');- const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');- expect(layout).toContain("import { registerDevCacheMenu } from '@/debug/devCacheMenu';");- expect(layout).toContain('registerDevCacheMenu();');- });-});diff --git a/apps/mobile/src/__tests__/deviceDetailProjectHeaderLayout.test.ts b/apps/mobile/src/__tests__/deviceDetailProjectHeaderLayout.test.tsindex 461c1f20e5..c20a5e9ba1 100644--- a/apps/mobile/src/__tests__/deviceDetailProjectHeaderLayout.test.ts+++ b/apps/mobile/src/__tests__/deviceDetailProjectHeaderLayout.test.ts@@ -1,42 +1,73 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { createElement, type ReactElement } from 'react';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';-const source = readFileSync(- resolve(process.cwd(), 'app/devices/[deviceId].tsx'),- 'utf8',-);--// 项目作用域页:iOS 不透明顶栏在 iOS 26+ 会被 react-native-screens 再垫一层顶部安全区,-// 标题栏下出现大块空白。页面必须走透明顶栏 + 由列表让出顶栏高度的整页滚动布局。-function projectScopeBranch(): string {- const start = source.indexOf('if (projectWorkingDir) {');- const end = source.indexOf('</ListDisclosureScope>', start);- expect(start).toBeGreaterThan(0);- expect(end).toBeGreaterThan(start);- return source.slice(start, end);+const source = ts.createSourceFile('screen.tsx', readFileSync(+ resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8',+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let branch = '';+function visit(node: ts.Node) {+ if (ts.isIfStatement(node) && node.expression.getText(source) === 'projectWorkingDir') {+ branch = node.thenStatement.getText(source);+ }+ ts.forEachChild(node, visit);}+visit(source);+if (!branch) throw new Error('Missing production project-scope render branch');+const compiled = ts.transpileModule('function renderProject() ' + branch, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React, jsxFactory: 'createElement' },+}).outputText;-describe('device detail project scope header layout', () => {- it('uses the transparent scroll-edge header', () => {- const branch = projectScopeBranch();- const header = branch.slice(branch.indexOf('<SimpleStackHeader'), branch.indexOf('/>', branch.indexOf('titleTestID="deviceDetail.title"')));-- expect(branch).toContain('simpleScrollScreenSafeAreaEdges()');- expect(header).toMatch(/^\s+scrollEdge\r?$/m);- });+type Element = ReactElement<Record<string, any>>;+function find(element: Element, type: string): Element | undefined {+ if (element?.type === type) return element;+ const children = [element?.props?.children, element?.props?.ListHeaderComponent].flat(Infinity);+ for (const child of children) {+ if (child && typeof child === 'object') {+ const result = find(child, type);+ if (result) return result;+ }+ }+}- it('renders the search entry inside the inset-adjusted list header', () => {- const branch = projectScopeBranch();- const listStart = branch.indexOf('<SectionList');- const listHeader = branch.indexOf('ListHeaderComponent=', listStart);- const searchActions = branch.indexOf('testID="deviceDetail.projectSearchActions"');- const searchRow = branch.indexOf("row: 'deviceDetail.projectSearchRow'");+// Unit: execute the production JSX branch and inspect delivered native props.+// iOS 26 double safe-area and Android Fabric clipping are separate regressions;+// source strings could pass even when later spreads overrode the effective props.+function renderProject(searchOpen: boolean) {+ const inset = { contentInsetAdjustmentBehavior: 'automatic' };+ const scope: Record<string, unknown> = {+ createElement, projectWorkingDir: '/project', sections: [], displaySections: [],+ showConnectionBanner: false, loading: false, status: 'connected', styles: {},+ simpleScrollScreenSafeAreaEdges: () => ['left', 'right', 'bottom'],+ simpleScrollInsetProps: inset, usesNativeStackHeader: () => true, headerHeight: 88,+ t: (key: string) => key, projectName: 'Project', deviceName: 'Computer', deviceId: 'device',+ goBackGuarded: vi.fn(), guardedPush: vi.fn(), router: {}, loadSessions: vi.fn(),+ colors: { textSecondary: 'secondary' }, spacing: { xxl: 24 }, disclosure: { controller: {} },+ viewport: null, searchOpen, searchQuery: '', indexedSearch: { activeFilterCount: 0 },+ searchFilterA11y: '', searchFilterMenu: {}, setSearchQuery: vi.fn(), setSearchOpen: vi.fn(),+ setSearchFilterOpen: vi.fn(), suppressListEmptyState: true, actionOverlays: null,+ };+ for (const name of ['SafeAreaView', 'SimpleStackHeader', 'View', 'ListDisclosureScope',+ 'SectionList', 'DeviceListCell', 'RefreshControl', 'HomeSearchBar', 'MainWindowActionGroup',+ 'RemoteListSyncingPlaceholder']) scope[name] = name;+ const tree = new Function(...Object.keys(scope), compiled + '; return renderProject();')(+ ...Object.values(scope),+ ) as Element;+ return { tree, inset };+}- expect(listStart).toBeGreaterThan(0);- expect(branch.slice(listStart, listHeader)).toContain('{...simpleScrollInsetProps}');- expect(listHeader).toBeGreaterThan(listStart);- expect(searchActions).toBeGreaterThan(listHeader);- expect(searchRow).toBeGreaterThan(listHeader);+describe('device detail project list native layout', () => {+ it.each([false, true])('delivers scroll-edge/inset/clipping props with searchOpen=%s', (searchOpen) => {+ const { tree, inset } = renderProject(searchOpen);+ expect(tree.props.edges).toEqual(['left', 'right', 'bottom']);+ expect(find(tree, 'SimpleStackHeader')?.props.scrollEdge).toBe(true);+ const list = find(tree, 'SectionList')!;+ expect(list.props).toMatchObject({ ...inset, removeClippedSubviews: false });+ const search = find(list.props.ListHeaderComponent, searchOpen ? 'HomeSearchBar' : 'MainWindowActionGroup');+ expect(search).toBeDefined();+ if (searchOpen) expect(search!.props.testIDs.row).toBe('deviceDetail.projectSearchRow');+ else expect(search!.props.testID).toBe('deviceDetail.projectSearchActions');});});diff --git a/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.ts b/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.tsdeleted file mode 100644index a30ba77304..0000000000--- a/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.ts+++ /dev/null@@ -1,20 +0,0 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--const source = readFileSync(- resolve(process.cwd(), 'app/devices/[deviceId].tsx'),- 'utf8',-);--describe('device detail project list Fabric lifecycle', () => {- it('keeps Android clipping disabled for the swipeable project list', () => {- const testIdIndex = source.indexOf('testID="deviceDetail.projectSessionList"');- const listStart = source.lastIndexOf('<SectionList', testIdIndex);- const listProps = source.slice(listStart, testIdIndex);-- expect(testIdIndex).toBeGreaterThan(0);- expect(listStart).toBeGreaterThan(0);- expect(listProps).toContain('removeClippedSubviews={false}');- });-});diff --git a/apps/mobile/src/__tests__/env.test.ts b/apps/mobile/src/__tests__/env.test.tsindex bc06b9b34a..975432f0ed 100644--- a/apps/mobile/src/__tests__/env.test.ts+++ b/apps/mobile/src/__tests__/env.test.ts@@ -1,5 +1,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import * as endpointContract from '@cindy/maker-shared/client-endpoints';import { describe, expect, it } from 'vitest';import {DEFAULT_DEVICE_LINK_API_BASE_URL,@@ -95,10 +98,37 @@ describe('mobile env', () => {});});- it('selects the bundled dev endpoint manifest from AUTH_REGION', () => {- const source = readFileSync(resolve(process.cwd(), 'src/config/env.ts'), 'utf8');- expect(source).toContain("AUTH_REGION === 'global'");- expect(source).toContain("require('../../../../config/endpoint.global.json')");- expect(source).toContain("require('../../../../config/endpoint.json')");+ // Unit: evaluate the actual module with isolated build inputs, preserving the+ // production parser. A wrong branch must change the public endpoint output;+ // checking that both require strings exist did not catch that regression.+ it('selects each bundled dev manifest and leaves production loading to startup', () => {+ const compiled = ts.transpileModule(+ readFileSync(resolve(process.cwd(), 'src/config/env.ts'), 'utf8'),+ { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } },+ ).outputText;+ const manifests = Object.fromEntries(['cn', 'global', 'dev'].map((region) => [+ `../../../../config/endpoint${region === 'cn' ? '' : `.${region}`}.json`,+ { schemaVersion: 1, authApiBaseUrl: `https://${region}.example.invalid` },+ ]));+ for (const region of ['cn', 'global', 'dev']) {+ for (const dev of [false, true]) {+ const exports: Record<string, unknown> = {};+ const loaded: string[] = [];+ runInNewContext(compiled, {+ exports, __DEV__: dev, process: { env: { EXPO_PUBLIC_CINDY_AUTH_REGION: region } },+ require(id: string) {+ if (id === 'expo-application') return {};+ if (id === 'expo-constants') return { default: { expoConfig: null } };+ if (id === '@cindy/maker-shared/client-endpoints') return endpointContract;+ if (id === './endpointManifestLoader') return {};+ if (Object.hasOwn(manifests, id)) { loaded.push(id); return manifests[id]; }+ throw new Error(`Unexpected module: ${id}`);+ },+ });+ expect(exports.AUTH_REGION).toBe(region);+ expect(exports.AUTH_API_BASE_URL).toBe(dev ? `https://${region}.example.invalid` : '');+ expect(loaded).toHaveLength(dev ? 1 : 0);+ }+ }});});diff --git a/apps/mobile/src/__tests__/filesConnectionBanner.test.ts b/apps/mobile/src/__tests__/filesConnectionBanner.test.tsindex d506983e87..a35e4adf6d 100644--- a/apps/mobile/src/__tests__/filesConnectionBanner.test.ts+++ b/apps/mobile/src/__tests__/filesConnectionBanner.test.ts@@ -1,26 +1,53 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import * as React from 'react';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { resolveConnectionBannerVisibility, resolveEffectiveConnectionError } from '@/components/connectionBannerVisibility';-describe('mobile files page connection banner noise budget', () => {- it('renders the connection banner only when the link is degraded, not as a resident bar', () => {- const source = readFileSync(resolve(process.cwd(), 'app/files/[sessionId].tsx'), 'utf8');- // 页面只有这一处 ConnectionBanner,下面的属性断言直接查全文即可绑定到它。- expect(source.split('<ConnectionBanner').length).toBe(2);+// Exercise the real page expressions and banner eligibility function; native paint is irrelevant.+const page = ts.createSourceFile('files.tsx', readFileSync(resolve(process.cwd(), 'app/files/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const banner = ts.createSourceFile('banner.tsx', readFileSync(resolve(process.cwd(), 'src/components/ConnectionBanner.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const hook = banner.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'useShowConnectionBanner');+if (!hook) throw new Error('Missing production banner eligibility function');+const hookCode = ts.transpileModule(hook.getText(banner).replace(/^export /, ''), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+const useShowConnectionBanner = new Function('resolveConnectionBannerVisibility', 'resolveEffectiveConnectionError', hookCode + '\nreturn useShowConnectionBanner;')(resolveConnectionBannerVisibility, resolveEffectiveConnectionError);+let visibility: ts.Expression | undefined, render: ts.Expression | undefined, footer: ts.Expression | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(page) === 'showConnectionBanner') visibility = node.initializer;+ if (ts.isJsxExpression(node) && node.expression && ts.isConditionalExpression(node.expression) && node.expression.whenTrue.getText(page).includes('<ConnectionBanner')) render = node.expression;+ if (ts.isJsxExpression(node) && node.expression?.getText(page).includes("t('files.browser.footerOnline')")) footer = node.expression;+ ts.forEachChild(node, visit);+}+visit(page);+function evaluate(expression: ts.Expression | undefined, bindings: Record<string, unknown>) {+ if (!expression) throw new Error('Missing production file-page expression');+ const code = ts.transpileModule('const result = ' + expression.getText(page) + ';', { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+ return new Function(...Object.keys(bindings), code + '\nreturn result;')(...Object.values(bindings));+}- // banner 渲染条件与会话页对齐(useShowConnectionBanner):请求级 error /- // 可分类连接问题 / 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线- // 持续超过防闪窗口后也显示;连接正常时不渲染常驻状态条。- expect(source).toContain('useShowConnectionBanner(status, error, connectionIssue, deviceUnresponsive)');- expect(source).toContain('{showConnectionBanner ? (');- expect(source).toContain('density="compact"');- expect(source).toContain('variant="inline"');+describe('mobile files page connection banner noise budget', () => {+ it.each([+ ['online', null, null, false, false],+ ['online', 'request failed', null, false, true],+ ['online', null, null, true, true],+ ['stopped', null, { kind: 'auth' }, false, true],+ ['stopped', null, null, false, true],+ ['connecting', null, null, false, false],+ ])('renders degraded-link feedback for %s/error=%s/issue=%s/unresponsive=%s', (status, error, connectionIssue, deviceUnresponsive, expected) => {+ const showConnectionBanner = evaluate(visibility, { useShowConnectionBanner, status, error, connectionIssue, deviceUnresponsive });+ const loadDirectory = vi.fn();+ const element = evaluate(render, { React, ConnectionBanner: 'connection-banner', showConnectionBanner, status, error, connectionIssue, deviceUnresponsive, lastSyncedAt: null, loading: false, loadDirectory });+ expect(element !== null).toBe(expected);+ if (element) {+ expect(element.props).toMatchObject({ density: 'compact', variant: 'inline', status, error, issue: connectionIssue, deviceUnresponsive });+ element.props.onSync();+ expect(loadDirectory).toHaveBeenCalledOnce();+ }});-- it('keeps the footer realtime-sync line as the only resident connection hint', () => {- const source = readFileSync(resolve(process.cwd(), 'app/files/[sessionId].tsx'), 'utf8');- // 文案已 i18n 化:常驻 footer 提示改由 catalog key 渲染(footerOnline / footerConnecting)。- expect(source).toContain("t('files.browser.footerOnline')");- expect(source).toContain("t('files.browser.footerConnecting')");+ it('keeps the footer realtime-sync hint available independently of the banner', () => {+ const t = (key: string) => key;+ expect(evaluate(footer, { notice: null, status: 'online', t })).toBe('files.browser.footerOnline');+ expect(evaluate(footer, { notice: null, status: 'connecting', t })).toBe('files.browser.footerConnecting');});});diff --git a/apps/mobile/src/__tests__/fixtures/messageRendererComponents.ts b/apps/mobile/src/__tests__/fixtures/messageRendererComponents.tsnew file mode 100644index 0000000000..4e5919e775--- /dev/null+++ b/apps/mobile/src/__tests__/fixtures/messageRendererComponents.ts@@ -0,0 +1,60 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import ts from 'typescript';+import { i18n } from '@/i18n';+import { logUnhandledRenderItem } from '@/session/assertNever';+import { useFoldableExpandedState } from '@/session/expandedBlockMemory';+import { buildMessageHierarchyLayout } from '@/session/messageHierarchyLayout';+import { formatLocalizedDuration } from '@/session/sessionDurationFormat';+import { iconSize, iconStroke, lightColors } from '@/theme/tokens';++// Run the actual internal components without loading the native message-list+// host or unrelated viewers. Only native view surfaces and unrelated children+// are adapted; routing, folding, account/device keys, and React hooks stay real.+export const rendererSource = ts.createSourceFile('MessageRenderer.tsx', readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+export function rendererFunction(name: string): ts.FunctionDeclaration | ts.FunctionExpression {+ let found: ts.FunctionDeclaration | ts.FunctionExpression | undefined;+ function visit(node: ts.Node) {+ if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name?.text === name) found = node;+ ts.forEachChild(node, visit);+ }+ visit(rendererSource);+ if (!found?.body) throw new Error('Message renderer function was not found: ' + name);+ return found;+}++export function executeRenderer<T>(code: string, globals: Record<string, unknown>): T {+ const emitted = ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;+ const bindings = { React, ...globals };+ return new Function(...Object.keys(bindings), emitted)(...Object.values(bindings));+}++type NativeProps = { children?: React.ReactNode; testID?: string; onPress?: () => void; expanded?: boolean; accessibilityLabel?: string; style?: unknown };+function View({ children, testID, style }: NativeProps) {+ return React.createElement('div', { 'data-testid': testID, 'data-style': JSON.stringify(style) }, children);+}+function Text({ children, testID, onPress }: NativeProps) {+ return React.createElement(onPress ? 'button' : 'span', { 'data-testid': testID, onClick: onPress }, children);+}+function Header({ children, testID, onPress, expanded, accessibilityLabel, style }: NativeProps) {+ return React.createElement('button', { 'data-testid': testID, onClick: onPress, 'aria-expanded': expanded, 'aria-label': accessibilityLabel, 'data-style': JSON.stringify(style) }, children);+}++export function collaborationRenderer() {+ const state = { accountGeneration: 1 };+ const declarations = ['RenderItemView', 'SubagentCard', 'CollabCardShell', 'FoldablePanel', 'Rail', 'OrcaCollabCard', 'agentTaskStatusLabel']+ .map(name => rendererFunction(name).getText(rendererSource)).join(String.fromCharCode(10));+ const bindings = { useMemo: React.useMemo, useState: React.useState, useEffect: React.useEffect, useCallback: React.useCallback, useTranslation, i18n, View, Text, useTheme: () => ({ colors: lightColors }),+ useThemedStyles: () => ({}), makeStyles: () => ({}),+ useAuth: () => ({ accountGeneration: state.accountGeneration }),+ useRecyclingState: React.useState, useFoldableExpandedState,+ buildMessageHierarchyLayout, formatLocalizedDuration, iconSize, iconStroke,+ Bot: () => null, ChevronDown: () => null, ChevronRight: () => null,+ FoldableHeaderButton: Header, logUnhandledRenderItem,+ MessageBubble: ({ item }: { item: { message: { body: string } } }) => React.createElement('span', null, item.message.body),+ };+ return { state, ...executeRenderer<Record<'RenderItemView' | 'SubagentCard' | 'OrcaCollabCard', React.ComponentType<any>>>(declarations+ + '; return { RenderItemView, SubagentCard, OrcaCollabCard };', bindings) };+}diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.tsindex 626f857812..186df4105b 100644--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts@@ -180,3 +180,63 @@ describe('live stream interruption wiring', () => {expect(unsubscribe).toContain('noteSessionLiveStreamsInterrupted(toSend);');});});++// guard: Persistent data boundary: evicting a render cache must never delete the offline history.+describe("mobileSessionMessageCache.test.ts call-site contracts", () => {+it('does not treat an empty in-memory render snapshot as a cache deletion', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');+ expect(source).toContain('空内存可能只是 regular LRU 淘汰');+ expect(source).toContain('if (messages.length === 0) return;');+ expect(source).toContain("if (retentionForSession(sessionId) === 'schedule')");+ });+});++// guard: remote-and-mobile-adaptation.md: stale session identity, loading cleanup, and retry generations cross the page/coordinator boundary.+describe("remoteSyncTask.test.ts call-site contracts", () => {+function readSessionScreenSource(): string {+ return readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');+}+it('clears loading when a queued sync is blocked for a newly-created session', () => {+ const source = readSessionScreenSource();+ expect(source).toContain(+ 'if (shouldBlockSessionSync(sessionId)) {\n if (!syncRun.isStale()) setLoading(false);\n return;\n }',+ );+ });++it('resets loading when the reused screen switches sessions', () => {+ const source = readSessionScreenSource();+ expect(source).toContain(+ 'setRewindState({ kind: \'idle\' });\n setMessageActionBusy(null);\n setLoading(false);',+ );+ });++it('uses the force-reopen callback for subscription and snapshot retries', () => {+ const source = readSessionScreenSource();+ expect(source).toContain(+ 'reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion)',+ );+ expect(source).toContain(+ 'await syncReopenCoordinator.reopenAfter(failedAtVersion);',+ );+ expect(source).toContain(+ 'const syncReopenCoordinator = createRemoteSyncReopenCoordinator(',+ );+ expect(source).not.toContain(+ 'reopenLink: async () => {\n await openLink(deviceId);\n }',+ );+ });++it('applies coordinator context and task changes after render commits', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/device-link/remoteSyncTask.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ expect(source).toContain(+ 'useLayoutEffect(() => {\n taskRef.current = task;\n coordinatorRef.current?.setContext(contextKey);\n }, [contextKey, task]);',+ );+ expect(source).not.toContain(+ ' taskRef.current = task;\n const coordinatorRef =',+ );+ expect(source).not.toContain('coordinatorRef.current.setContext(contextKey);');+ });+});diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 1ee6e5f03e..7e014eddc6 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -853,3 +853,118 @@ describe('home menu presentation', () => {expect(home).toContain('pendingMenuActionRef.current = () => setSearchOpen(true);');});});++// Guard: remote-and-mobile-adaptation lifecycle/ownership contract. HomeSurface+// must coordinate freshness tokens, shared remote-store reseeds and schedule+// event generations; reordered commits can clear a newer request or miss rows+// while Home is covered. Unit planner/store behavior remains in homeListFreshness.+describe('Home list sync wiring', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8').replace(/\r\n/g, '\n');++ it('keeps the visible-device sync scope while Home is covered', () => {+ const scope = source.slice(source.indexOf('const homeSyncDeviceIds = useMemo('), source.indexOf('const homeSyncDeviceIdSet'));+ expect(scope).toContain('resolveHomeDeviceSyncIds(');+ expect(scope).not.toContain('screenFocused');+ // Devices that stop being visible/usable are still released and unsubscribed.+ const reconcile = source.slice(source.indexOf('const reconcileHomeDeviceSyncScope'), source.indexOf('useEffect(() => () => {'));+ expect(reconcile).toMatch(/for \(const deviceId of diff\.release\) \{[\s\S]*homeListFreshnessRef\.current\.invalidate\(deviceId\);[\s\S]*releaseHomeListOwner\(deviceId\);/);+ expect(source).toContain("void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);");+ });++ it('records freshness only after a successful list pull and invalidates on failure', () => {+ const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));+ const capture = hydrate.indexOf('homeListFreshnessRef.current.capture(device.deviceId)');+ const subscribe = hydrate.indexOf("await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);");+ const list = hydrate.indexOf("'local-db:sessions:list'");+ const applied = hydrate.indexOf('remoteSessionStore.setDeviceSessions(');+ const fresh = hydrate.indexOf('homeListFreshnessRef.current.markFresh(');+ expect(capture).toBeGreaterThan(-1);+ expect(capture).toBeLessThan(subscribe);+ expect(subscribe).toBeLessThan(list);+ expect(applied).toBeLessThan(fresh);+ expect(hydrate.slice(hydrate.indexOf('} catch (err) {'))).toContain('homeListFreshnessRef.current.invalidate(device.deviceId);');+ });++ it('refills only stale devices on focus return and keeps the full sync for other triggers', () => {+ const focus = source.slice(source.indexOf('const refillStaleHomeDevices = useCallback('), source.indexOf('// 把当前权威设备列表注入 remoteSessionStore'));+ expect(focus).toContain('screenFocusedRef.current = true;');+ expect(focus).toContain('const plan = planHomeListFocusReturn({');+ expect(focus).toMatch(/if \(plan\.kind === 'refill'\) \{\s*refillStaleHomeDevices\(plan\.deviceIds\);\s*if \(scheduleDirty\.size > 0\) refreshHomeScheduleIndexes\(scheduleDirty\);\s*return;\s*\}\s*refreshHomeScheduleIndexes\(\);\s*startSilentHomeSync\(\);/);+ expect(focus).toContain("if (nextState === 'background') homeListFreshnessRef.current.invalidateAll();");+ expect(focus).toContain("if (nextState === 'active') startSilentHomeSync();");+ });++ it('keeps a full-reload request from every full-sync trigger until a loadHome started after it commits', () => {+ // Invariant: any trigger needing a full sync (mount, foreground, reconnect, a full focus return,+ // dependency changes) leaves a request that only a later-started, committed loadHome clears.+ // A sync that fails, is skipped while covered or exits because Home blurred mid-flight keeps it,+ // so a quick return cannot downgrade to a device-row refill and miss bound/unbound computers.+ const silent = source.slice(source.indexOf('const startSilentHomeSync = useCallback(() => {'), source.indexOf('}, [deviceIdentityCacheReady, homeListCacheHydrated'));+ expect(silent.indexOf('requestHomeFullReload();')).toBeGreaterThan(-1);+ expect(silent.indexOf('requestHomeFullReload();')).toBeLessThan(silent.indexOf('if (!screenFocusedRef.current) return;'));+ // Single funnel: no other call site sets the request, nothing but a commit or account reset clears it.+ expect(source.match(/requestHomeFullReload\(\);/g)).toHaveLength(1);+ expect(source.match(/homeFullReloadOnFocusRef\.current = null/g)).toHaveLength(2);+ const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));+ const focusBody = focus.slice(0, focus.indexOf('}, [refillStaleHomeDevices'));+ expect(focusBody).toContain('const forceFull = homeFullReloadOnFocusRef.current !== null;');+ const load = source.slice(source.indexOf('const loadHome = useCallback('), source.indexOf('loadHomeRef.current = loadHome;'));+ expect(load.indexOf('const fullReloadRequestAtStart = homeFullReloadOnFocusRef.current;'))+ .toBeLessThan(load.indexOf('const rawTask = (async () => {'));+ // Blurring after the device-list read exits before the commit, leaving the request in place.+ expect(load.indexOf('if (!screenFocusedRef.current) return;')).toBeLessThan(load.indexOf('lastSyncedAtRef.current = now;'));+ const commit = load.slice(load.indexOf('lastSyncedAtRef.current = now;'));+ expect(commit).toContain('if (homeFullReloadOnFocusRef.current === fullReloadRequestAtStart) homeFullReloadOnFocusRef.current = null;');+ });++ it('refreshes automation badges on return only for devices that sent schedule events while away', () => {+ const events = source.slice(source.indexOf('useEffect(() => remoteScheduleEventStore.subscribe('), source.indexOf('const refreshHomeScheduleIndexes = useCallback('));+ expect(events).toMatch(/if \(!screenFocusedRef\.current\) \{\s*markHomeScheduleIndexDirty\(deviceId\);\s*continue;\s*\}\s*refreshDeviceScheduleIndex\(deviceId, sessionIds\);/);+ // The old unconditional "refresh every device on focus" effect is gone.+ expect(source).not.toContain('兜底刷新一次 scheduleIndex');+ const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));+ expect(focus.indexOf('screenFocusedRef.current = true;')).toBeLessThan(focus.indexOf('refreshHomeScheduleIndexes('));+ expect(focus).toContain('const scheduleDirty = new Set(homeScheduleIndexDirtyRef.current.keys());');+ });++ it('keeps automation badge refreshes pending until one is applied', () => {+ const refresh = source.slice(source.indexOf('const refreshDeviceScheduleIndex = useCallback('), source.indexOf('const hydrateDeviceSessionsOnce = useCallback('));+ // Recorded before the focus gate, so a skipped refresh or a dropped in-flight result is refilled on return.+ expect(refresh.indexOf('const pendingSeq = markHomeScheduleIndexDirty(deviceId);'))+ .toBeLessThan(refresh.indexOf("if (!screenFocusedRef.current || AppState.currentState !== 'active') return;"));+ const apply = refresh.slice(refresh.indexOf('setScheduleIndex((current) => replaceSessionScheduleIndexEntries('));+ expect(apply).toMatch(/if \(homeScheduleIndexDirtyRef\.current\.get\(deviceId\) === pendingSeq\) \{\s*homeScheduleIndexDirtyRef\.current\.delete\(deviceId\);/);+ const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));+ expect(hydrate.indexOf('markHomeScheduleIndexDirty(device.deviceId);'))+ .toBeLessThan(hydrate.indexOf('scheduleIndexDeferRegistryRef.current.schedule(device.deviceId'));+ expect(hydrate).toContain('nextSessions.length >= LIST_LIMIT');+ expect(hydrate).toContain('remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId)');+ });++ it('marks a device stale whenever its list asks for a reseed, even while Home is covered', () => {+ const reseed = source.slice(source.indexOf('remoteSessionStore.registerReseedHandler(item.device.deviceId'));+ expect(reseed.indexOf('homeListFreshnessRef.current.invalidate(item.device.deviceId);'))+ .toBeLessThan(reseed.indexOf('void hydrateDeviceSessions(item.device, accountGeneration'));+ });++ it('clears freshness with the rest of the account-owned Home state', () => {+ const reset = source.slice(source.indexOf('useLayoutEffect(() => {\n syncInFlightRef.current = null;'), source.indexOf('}, [accountGeneration]);'));+ expect(reset).toContain('homeListFreshnessRef.current.clear();');+ expect(reset).toContain('homeFullReloadOnFocusRef.current = null;');+ expect(reset).toContain('homeScheduleIndexDirtyRef.current.clear();');+ });+});+++// Guard: list projection and per-row usage subscriptions are one cross-file data contract.+describe('Home usage subscription contract', () => {+ const meta = readSource('src/session/HomeSessionInfoMeta.tsx');+ const store = readSource('src/session/remoteSessionStore.ts');+ it('reads token / cost per row because the Home projection strips usage fields', () => {+ // Home 列表投影刻意去掉用量(避免用量推送重排分组),行上的 Token / 费用必须单独订阅。+ expect(store).toContain('delete projected.totalTokenUsage;');+ expect(meta).toContain("taskInfoFields.includes('tokens') || taskInfoFields.includes('cost')");+ expect(meta.match(/useRemoteSessionUsage\(/g)?.length).toBe(2);+ });++});diff --git a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts b/apps/mobile/src/__tests__/homeDisplaySettings.test.tsindex 68d2d08d31..5d67d7861f 100644--- a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts+++ b/apps/mobile/src/__tests__/homeDisplaySettings.test.ts@@ -1,3 +1,5 @@+import ts from 'typescript';+import { buildMobileHomePresentation } from '@/session/mobileHome';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -182,60 +184,101 @@ describe('task info pieces (desktop 任务信息 parity)', () => {});});-describe('task info usage wiring', () => {- const meta = readFileSync(resolve(process.cwd(), 'src/session/HomeSessionInfoMeta.tsx'), 'utf8');- const store = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');-- it('reads token / cost per row because the Home projection strips usage fields', () => {- // Home 列表投影刻意去掉用量(避免用量推送重排分组),行上的 Token / 费用必须单独订阅。- expect(store).toContain('delete projected.totalTokenUsage;');- expect(meta).toContain("taskInfoFields.includes('tokens') || taskInfoFields.includes('cost')");- expect(meta.match(/useRemoteSessionUsage\(/g)?.length).toBe(2);- });+const surface = ts.createSourceFile('home.tsx', readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function evaluate(node: ts.Node, file: ts.SourceFile, scope: Record<string, unknown>): any {+ const compiled = ts.transpileModule('function evaluate() { return (' + node.getText(file) + '); }', {+ compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },+ }).outputText;+ return new Function(...Object.keys(scope), compiled + '; return evaluate();')(...Object.values(scope));+}+function surfaceValue(name: string, scope: Record<string, unknown>): any {+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (!initializer && ts.isVariableDeclaration(node) && node.name.getText(surface) === name) initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(surface);+ if (!initializer) throw new Error('Missing production Home initializer: ' + name);+ return evaluate(initializer, surface, scope);+}+const useMemo = (build: () => unknown) => build();- it('keeps worktree off the mobile task info (desktop-only per sidebar plan §3.4)', async () => {- const { HOME_TASK_INFO_FIELDS, normalizeTaskInfoFields } = await import('@/session/homeDisplaySettings');- expect(HOME_TASK_INFO_FIELDS).toEqual(['time', 'pr', 'tokens', 'cost']);- // 旧版本存下的 worktree 勾选被丢弃。+describe('task info and retained Home behavior', () => {+ it('keeps worktree off the mobile task info (desktop-only per sidebar plan 3.4)', async () => {+ const { normalizeTaskInfoFields } = await import('@/session/homeDisplaySettings');expect(normalizeTaskInfoFields(['worktree', 'pr'])).toEqual(['pr']);});- it('counts dialogue automation runs like project candidates', () => {- const surface = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- expect(surface).toContain('dialogueCount: projectFilterUniverse.chats.reduce((sum, item) => sum + (item.automationGroup?.sessionCount ?? 1), 0),');+ it('counts each dialogue automation run in the actual display-menu input', () => {+ const projectFilterUniverse = { chats: [item('normal'), { ...item('automation'), automationGroup: { sessionCount: 4 } }], projects: [] };+ const options = surfaceValue('homeDisplayPullDownActions', { useMemo, projectFilterUniverse,+ selectedDeviceId: null, displayMenuState: {}, t: (key: string) => key,+ buildHomeDisplayPullDownActions: (value: unknown) => value });+ expect(options.dialogueCount).toBe(5);});- it('reorders only the filtered visible projects and keeps hidden project slots', () => {- // 完整顺序 A、B、C,筛选后只显示 A / C,把 C 拖到 A 前:B 保持原槽位。- expect(reorderVisibleProjectByDropIndex(['A', 'B', 'C'], ['A', 'C'], 'C', 0)).toEqual(['C', 'B', 'A']);- const surface = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- // 主机账本分支的可见集同样取实际渲染(已筛选)的项目。- expect(surface).toContain('const visibleKeys = visibleProjectKeys.filter((key) => hostWritable.has(key));');+ it('keeps hidden project slots when applying the actual host-visible subset', () => {+ const visible = surfaceValue('visibleKeys', { visibleProjectKeys: ['A', 'C', 'read-only'], hostWritable: new Set(['A', 'B', 'C']) });+ expect(reorderVisibleProjectByDropIndex(['A', 'B', 'C'], visible, 'C', 0)).toEqual(['C', 'B', 'A']);});- it('lists project filter candidates regardless of search and status', () => {- // 已选中的项目不能因为搜索没命中或当前状态下没有任务而从菜单消失。- const surface = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- const universe = surface.slice(surface.indexOf('const projectFilterUniverse = useMemo('), surface.indexOf('const projectMachineIdentities'));- expect(universe).toContain("statusFilter: 'all',");- expect(universe).not.toContain('searchQuery');- expect(surface).toContain('projects: projectFilterUniverse.projects.map((project) => ({');+ it('keeps real project candidates available despite nonmatching search and status', () => {+ const sessions = ['A', 'B'].map((name) => ({ ...item(name).session, title: name, workingDir: '/' + name,+ workspaceKind: 'project', status: 'active', deviceLinkDeviceId: 'd', deviceLinkDeviceName: 'Computer' }));+ const result = surfaceValue('projectFilterUniverse', { useMemo, buildMobileHomePresentation,+ deviceModels: [], scheduleIndex: new Map(), selectedDeviceId: null, homeSessions: sessions,+ t: (key: string) => key, searchQuery: 'no match', statusFilter: 'running' });+ expect(result.projects.map((project: { workingDir: string }) => project.workingDir).sort()).toEqual(['/A', '/B']);});- it('re-evaluates the last-activity filter on a clock while the list stays open', () => {- const surface = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- expect(surface).toContain("const filterTick = useHomeFilterClock(lastActivityFilter !== 'all' && screenFocused);");- expect(surface).toContain('applyHomeContentFilters(sharedGroup.home, contentFilters, filterTick || Date.now())');+ it('expires active-time rows using the actual clock input while Home stays open', () => {+ for (const [filter, focused, enabled] of [['all', true, false], ['1d', false, false], ['1d', true, true]] as const) {+ expect(surfaceValue('filterTick', { lastActivityFilter: filter, screenFocused: focused,+ useHomeFilterClock: (active: boolean) => active })).toBe(enabled);+ }+ const input = home({ chats: [item('recent', { daysAgo: 0.5 })] });+ const scope = { useMemo, sharedGroup: { home: input }, applyHomeContentFilters,+ contentFilters: { ...NO_FILTERS, lastActivity: '1d' } };+ expect(surfaceValue('filteredHome', { ...scope, filterTick: NOW }).chats).toHaveLength(1);+ expect(surfaceValue('filteredHome', { ...scope, filterTick: NOW + DAY }).chats).toHaveLength(0);});- it('polls PR status only while the retained home list is visible', () => {- // 首页被盖住时任务行仍挂载:轮询前检查可见性,回到首页时补查一次。- expect(meta).toContain("if (AppState.currentState !== 'active' || !isActive()) return;");- expect(meta).toContain('const stopResume = onResume(() => refresh(true));');- // 节流补查与回到前台补查。- expect(meta).toContain('if (retryIn > 0 && retry === undefined) {');- expect(meta).toContain("if (state === 'active') refresh(true);");- expect(store).toContain('export function useRemoteSessionStoreVisibility()');+ it('pauses PR polling under another page and refreshes on resume, with cleanup', () => {+ const file = ts.createSourceFile('meta.tsx', readFileSync(resolve(process.cwd(), 'src/session/HomeSessionInfoMeta.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const hook = file.statements.find((node): node is ts.FunctionDeclaration => ts.isFunctionDeclaration(node) && node.name?.text === 'useHomeSessionPr');+ let callback: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isCallExpression(node) && node.expression.getText(file) === 'useEffect') callback = node.arguments[0];+ ts.forEachChild(node, visit);+ }+ if (!hook) throw new Error('Missing PR hook');+ visit(hook);+ if (!callback) throw new Error('Missing PR lifecycle effect');+ let visible = true;+ let poll!: () => void;+ let resume!: () => void;+ let foreground!: (state: string) => void;+ const remove = vi.fn(), stopResume = vi.fn(), clearInterval = vi.fn();+ const refreshHomeSessionPr = vi.fn((_key: string, _load: () => unknown, _options: unknown) => 0);+ const AppState = { currentState: 'active', addEventListener: (_event: string, callback: typeof foreground) => { foreground = callback; return { remove }; } };+ const effect = evaluate(callback, file, { key: 'cache', deviceId: 'd', sessionId: 's', online: true,+ isActive: () => visible, AppState, refreshHomeSessionPr, loadHomeSessionPr: vi.fn(), link: {}, refreshKey: 'updated',+ PR_STATUS_REFRESH_INTERVAL_MS: 90_000, Date, clearInterval, clearTimeout: vi.fn(),+ setInterval: (fn: () => void) => { poll = fn; return 1; }, setTimeout: vi.fn(),+ onResume: (fn: () => void) => { resume = fn; return stopResume; } });+ const cleanup = effect();+ expect(refreshHomeSessionPr).toHaveBeenCalledTimes(1);+ visible = false; poll(); resume();+ expect(refreshHomeSessionPr).toHaveBeenCalledTimes(1);+ visible = true; resume();+ expect(refreshHomeSessionPr).toHaveBeenCalledTimes(2);+ expect(refreshHomeSessionPr.mock.calls[1]?.[2]).toMatchObject({ eventful: true });+ AppState.currentState = 'background'; poll();+ expect(refreshHomeSessionPr).toHaveBeenCalledTimes(2);+ AppState.currentState = 'active'; foreground('active');+ expect(refreshHomeSessionPr).toHaveBeenCalledTimes(3);+ cleanup(); expect(clearInterval).toHaveBeenCalledWith(1);+ expect(remove).toHaveBeenCalledOnce(); expect(stopResume).toHaveBeenCalledOnce();});});diff --git a/apps/mobile/src/__tests__/homeListFreshness.test.ts b/apps/mobile/src/__tests__/homeListFreshness.test.tsindex 32763018bc..9ce15a4c5b 100644--- a/apps/mobile/src/__tests__/homeListFreshness.test.ts+++ b/apps/mobile/src/__tests__/homeListFreshness.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import { rehydrateDeviceLinkPeer, type DeviceLinkRehydrateDeps } from '@/device-link/rehydrate';import {@@ -167,100 +165,3 @@ describe('Home list freshness on return', () => {expect(home.freshness.isFresh('mac')).toBe(false);});});--describe('Home list sync wiring', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8').replace(/\r\n/g, '\n');-- it('keeps the visible-device sync scope while Home is covered', () => {- const scope = source.slice(source.indexOf('const homeSyncDeviceIds = useMemo('), source.indexOf('const homeSyncDeviceIdSet'));- expect(scope).toContain('resolveHomeDeviceSyncIds(');- expect(scope).not.toContain('screenFocused');- // Devices that stop being visible/usable are still released and unsubscribed.- const reconcile = source.slice(source.indexOf('const reconcileHomeDeviceSyncScope'), source.indexOf('useEffect(() => () => {'));- expect(reconcile).toMatch(/for \(const deviceId of diff\.release\) \{[\s\S]*homeListFreshnessRef\.current\.invalidate\(deviceId\);[\s\S]*releaseHomeListOwner\(deviceId\);/);- expect(source).toContain("void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);");- });-- it('records freshness only after a successful list pull and invalidates on failure', () => {- const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));- const capture = hydrate.indexOf('homeListFreshnessRef.current.capture(device.deviceId)');- const subscribe = hydrate.indexOf("await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);");- const list = hydrate.indexOf("'local-db:sessions:list'");- const applied = hydrate.indexOf('remoteSessionStore.setDeviceSessions(');- const fresh = hydrate.indexOf('homeListFreshnessRef.current.markFresh(');- expect(capture).toBeGreaterThan(-1);- expect(capture).toBeLessThan(subscribe);- expect(subscribe).toBeLessThan(list);- expect(applied).toBeLessThan(fresh);- expect(hydrate.slice(hydrate.indexOf('} catch (err) {'))).toContain('homeListFreshnessRef.current.invalidate(device.deviceId);');- });-- it('refills only stale devices on focus return and keeps the full sync for other triggers', () => {- const focus = source.slice(source.indexOf('const refillStaleHomeDevices = useCallback('), source.indexOf('// 把当前权威设备列表注入 remoteSessionStore'));- expect(focus).toContain('screenFocusedRef.current = true;');- expect(focus).toContain('const plan = planHomeListFocusReturn({');- expect(focus).toMatch(/if \(plan\.kind === 'refill'\) \{\s*refillStaleHomeDevices\(plan\.deviceIds\);\s*if \(scheduleDirty\.size > 0\) refreshHomeScheduleIndexes\(scheduleDirty\);\s*return;\s*\}\s*refreshHomeScheduleIndexes\(\);\s*startSilentHomeSync\(\);/);- expect(focus).toContain("if (nextState === 'background') homeListFreshnessRef.current.invalidateAll();");- expect(focus).toContain("if (nextState === 'active') startSilentHomeSync();");- });-- it('keeps a full-reload request from every full-sync trigger until a loadHome started after it commits', () => {- // Invariant: any trigger needing a full sync (mount, foreground, reconnect, a full focus return,- // dependency changes) leaves a request that only a later-started, committed loadHome clears.- // A sync that fails, is skipped while covered or exits because Home blurred mid-flight keeps it,- // so a quick return cannot downgrade to a device-row refill and miss bound/unbound computers.- const silent = source.slice(source.indexOf('const startSilentHomeSync = useCallback(() => {'), source.indexOf('}, [deviceIdentityCacheReady, homeListCacheHydrated'));- expect(silent.indexOf('requestHomeFullReload();')).toBeGreaterThan(-1);- expect(silent.indexOf('requestHomeFullReload();')).toBeLessThan(silent.indexOf('if (!screenFocusedRef.current) return;'));- // Single funnel: no other call site sets the request, nothing but a commit or account reset clears it.- expect(source.match(/requestHomeFullReload\(\);/g)).toHaveLength(1);- expect(source.match(/homeFullReloadOnFocusRef\.current = null/g)).toHaveLength(2);- const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));- const focusBody = focus.slice(0, focus.indexOf('}, [refillStaleHomeDevices'));- expect(focusBody).toContain('const forceFull = homeFullReloadOnFocusRef.current !== null;');- const load = source.slice(source.indexOf('const loadHome = useCallback('), source.indexOf('loadHomeRef.current = loadHome;'));- expect(load.indexOf('const fullReloadRequestAtStart = homeFullReloadOnFocusRef.current;'))- .toBeLessThan(load.indexOf('const rawTask = (async () => {'));- // Blurring after the device-list read exits before the commit, leaving the request in place.- expect(load.indexOf('if (!screenFocusedRef.current) return;')).toBeLessThan(load.indexOf('lastSyncedAtRef.current = now;'));- const commit = load.slice(load.indexOf('lastSyncedAtRef.current = now;'));- expect(commit).toContain('if (homeFullReloadOnFocusRef.current === fullReloadRequestAtStart) homeFullReloadOnFocusRef.current = null;');- });-- it('refreshes automation badges on return only for devices that sent schedule events while away', () => {- const events = source.slice(source.indexOf('useEffect(() => remoteScheduleEventStore.subscribe('), source.indexOf('const refreshHomeScheduleIndexes = useCallback('));- expect(events).toMatch(/if \(!screenFocusedRef\.current\) \{\s*markHomeScheduleIndexDirty\(deviceId\);\s*continue;\s*\}\s*refreshDeviceScheduleIndex\(deviceId, sessionIds\);/);- // The old unconditional "refresh every device on focus" effect is gone.- expect(source).not.toContain('兜底刷新一次 scheduleIndex');- const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));- expect(focus.indexOf('screenFocusedRef.current = true;')).toBeLessThan(focus.indexOf('refreshHomeScheduleIndexes('));- expect(focus).toContain('const scheduleDirty = new Set(homeScheduleIndexDirtyRef.current.keys());');- });-- it('keeps automation badge refreshes pending until one is applied', () => {- const refresh = source.slice(source.indexOf('const refreshDeviceScheduleIndex = useCallback('), source.indexOf('const hydrateDeviceSessionsOnce = useCallback('));- // Recorded before the focus gate, so a skipped refresh or a dropped in-flight result is refilled on return.- expect(refresh.indexOf('const pendingSeq = markHomeScheduleIndexDirty(deviceId);'))- .toBeLessThan(refresh.indexOf("if (!screenFocusedRef.current || AppState.currentState !== 'active') return;"));- const apply = refresh.slice(refresh.indexOf('setScheduleIndex((current) => replaceSessionScheduleIndexEntries('));- expect(apply).toMatch(/if \(homeScheduleIndexDirtyRef\.current\.get\(deviceId\) === pendingSeq\) \{\s*homeScheduleIndexDirtyRef\.current\.delete\(deviceId\);/);- const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));- expect(hydrate.indexOf('markHomeScheduleIndexDirty(device.deviceId);'))- .toBeLessThan(hydrate.indexOf('scheduleIndexDeferRegistryRef.current.schedule(device.deviceId'));- expect(hydrate).toContain('nextSessions.length >= LIST_LIMIT');- expect(hydrate).toContain('remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId)');- });-- it('marks a device stale whenever its list asks for a reseed, even while Home is covered', () => {- const reseed = source.slice(source.indexOf('remoteSessionStore.registerReseedHandler(item.device.deviceId'));- expect(reseed.indexOf('homeListFreshnessRef.current.invalidate(item.device.deviceId);'))- .toBeLessThan(reseed.indexOf('void hydrateDeviceSessions(item.device, accountGeneration'));- });-- it('clears freshness with the rest of the account-owned Home state', () => {- const reset = source.slice(source.indexOf('useLayoutEffect(() => {\n syncInFlightRef.current = null;'), source.indexOf('}, [accountGeneration]);'));- expect(reset).toContain('homeListFreshnessRef.current.clear();');- expect(reset).toContain('homeFullReloadOnFocusRef.current = null;');- expect(reset).toContain('homeScheduleIndexDirtyRef.current.clear();');- });-});diff --git a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts b/apps/mobile/src/__tests__/homeProjectChildWindow.test.tsindex 87217f4bdd..e093a2688e 100644--- a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts+++ b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts@@ -117,25 +117,25 @@ describe('home project child window', () => {});it('keeps layout readiness out of the first-render window gate', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- const setupStart = source.indexOf('const windowingEnabled = shouldWindowHomeProjectChildren({');- const setupEnd = source.indexOf('const scrollY = homeScrollY;', setupStart);- const setup = source.slice(setupStart, setupEnd);-- expect(setupStart).toBeGreaterThan(-1);- expect(setup).not.toContain('projectLayoutReady');- expect(source).toContain('function HomeProjectWindowAnchorTracker({');- expect(source).toContain('const layout = measure(projectRef);');- expect(source).toContain('projectTop: layout.pageY,');- expect(source).toContain('viewportTop: 0,');- expect(source).toContain('if (next === null || next === previous) return;');- expect(source).not.toContain('projectRef.current?.measureInWindow');- expect(source).toContain('return resolveHomeProjectChildAnchor({');- expect(source).toContain('const [windowAnchor, setWindowAnchor] = useState(-1);');- expect(source).toContain('trailingSpacerHeight: childContentHeight');- expect(source).toContain('{windowingEnabled && scrollY ? (');- expect(source).toContain('const renderedSessions = windowingEnabled ? visibleSessions.slice');- expect(source).toContain('if (!windowingEnabled) return;');+ const file = ts.createSourceFile('screen.tsx', readFileSync(+ resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8',+ ), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: ts.Expression | undefined;+ const visit = (node: ts.Node) => {+ if (!initializer && ts.isVariableDeclaration(node) && node.name.getText(file) === 'windowingEnabled') {+ initializer = node.initializer;+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ if (!initializer) throw new Error('Missing production child-window gate');+ const evaluate = new Function('shouldWindowHomeProjectChildren', 'collapsed', 'visibleSessions',+ 'homeScrollY', 'projectLayoutReady', 'PROJECT_CHILD_WINDOW_THRESHOLD',+ 'return (' + initializer.getText(file) + ');');+ // Execute the real first-render gate before native layout exists. The old+ // readiness dependency mounted the full 200-row tree before windowing began.+ expect(evaluate(shouldWindowHomeProjectChildren, false, Array(200), {}, false, 20)).toBe(true);+ expect(evaluate(shouldWindowHomeProjectChildren, true, Array(200), {}, false, 20)).toBe(false);});it('bounds the outer home list window instead of retaining every flat row', () => {@@ -143,7 +143,7 @@ describe('home project child window', () => {const readBatch = (attribute: string, platform: string, grouped: boolean) => {const expression = source.match(new RegExp(`${attribute}=\\{([^}]+)\\}`))?.[1];- expect(expression).toBeDefined();+ if (!expression) throw new Error('Missing production list batch expression: ' + attribute);return new Function('Platform', 'groupByProject', 'HOME_LIST_INITIAL_RENDER_COUNT', 'HOME_LIST_RENDER_BATCH_SIZE',`return (${expression});`)({ OS: platform }, grouped, 12, 12);};@@ -153,8 +153,6 @@ describe('home project child window', () => {expect(readBatch('maxToRenderPerBatch', platform, grouped)).toBe(platform === 'android' && grouped ? 2 : 12);}}- expect(source).toContain('updateCellsBatchingPeriod={32}');- expect(source).toContain('windowSize={HOME_LIST_WINDOW_SIZE}');});it('keeps the last visible project rows mounted when scrolling down and back up', () => {diff --git a/apps/mobile/src/__tests__/hookSourceRendering.test.ts b/apps/mobile/src/__tests__/hookSourceRendering.test.tsindex 3b5915bed6..8bd3d99752 100644--- a/apps/mobile/src/__tests__/hookSourceRendering.test.ts+++ b/apps/mobile/src/__tests__/hookSourceRendering.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { beforeAll, describe, expect, it } from 'vitest';@@ -10,24 +8,6 @@ import {isMobileImPlatform,} from '@/session/messageSourceLabels';-describe('mobile shared Cindy source card wiring', () => {- it('downgrades only legacy hook rows (stored prompt) and keeps local IM rows as user rows', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain('&& !item.message.hookSource.userTextContent');- expect(source).toContain("kind: 'system' as const, align: 'agent' as const");- expect(source).toContain('testID="message.hookSource"');- // 抬头走 i18n「Cindy · 来自 {{platform}}」,不再硬编码 Slack / Telegram / X。- expect(source).toContain('{imSourceHeaderTitle(hookSource.im)}');- expect(source).not.toContain("hookSource.im === 'x' ? 'X' : 'Slack'");- expect(source).toContain('{hookSource.channelName}');- // IM 卡片与桌面一样左对齐;长正文仍走有界测量与折叠保护。- expect(source).toContain('presentation.isUserAligned && !item.message.hookSource');- expect(source).toContain('(isUser || hookSource !== undefined)');- expect(source).toContain("(item.message.kind === 'user' || hookSource !== undefined)");- });-});-describe('IM source header text', () => {beforeAll(async () => {await i18n.changeLanguage('zh-CN');diff --git a/apps/mobile/src/__tests__/hostManagedSession.test.ts b/apps/mobile/src/__tests__/hostManagedSession.test.tsindex de18270e8d..1c7a4d4921 100644--- a/apps/mobile/src/__tests__/hostManagedSession.test.ts+++ b/apps/mobile/src/__tests__/hostManagedSession.test.ts@@ -1,6 +1,4 @@import { describe, expect, it } from 'vitest';-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { isHostManagedSession } from '@/session/hostManagedSession';@@ -10,28 +8,4 @@ describe('host-managed Session presentation', () => {expect(isHostManagedSession({ source: 'desktop' })).toBe(false);expect(isHostManagedSession(null)).toBe(false);});-- it('hides host-owned settings while preserving permission controls and the composer', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- expect(source).toContain('const sessionManagedByHost = useHostManagedSession(');- expect(source).toContain('messageOnly={sessionManagedByHost}');- const details = readFileSync(resolve(process.cwd(), 'src/session/SessionMenuSheet.tsx'), 'utf8');- expect(details).toContain('visible && !messageOnly');- expect(details).toContain('const mainActions = messageOnly ? []');- expect(details).toContain('const deleteAction = messageOnly ? undefined');- expect(details).toContain("!messageOnly && view === 'info'");- expect(source).toContain('{renderSessionPermissionButton()}');- expect(source).toContain('currentSession && runtimeOptions ? (');- expect(source).not.toContain('!sessionManagedByHost ? renderSessionPermissionButton() : null');- expect(source).toContain('{!sessionManagedByHost && composerRuntimeSummary ? (');- const modelAccess = source.slice(source.indexOf('const canConfigureSessionModel'), source.indexOf('// 共享模型自造'));- expect(modelAccess).toContain('canUseRemoteSessionControls');- expect(modelAccess).toContain('!sessionManagedByHost');- expect(modelAccess).toContain('!isSharedTaskPeer(deviceId)');- const modelPicker = source.slice(source.indexOf('const toggleComposerModelPicker'), source.indexOf('// 账号限额按需拉取'));- expect(modelPicker).toContain('if (!canConfigureSessionModel)');- expect(modelPicker).toContain('setModelSheetOpen(false);');- expect(source).toContain('{renderComposerAttachmentButton()}');- expect(source).toContain('{renderComposerInlineStop()}');- });});diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.tsindex 5d69f97279..6f4a5822a8 100644--- a/apps/mobile/src/__tests__/interactionModel.test.ts+++ b/apps/mobile/src/__tests__/interactionModel.test.ts@@ -2,6 +2,8 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { beforeAll, describe, expect, it } from 'vitest';import { i18n } from '@/i18n';+import ts from 'typescript';+import { remoteSessionStore } from '@/session/remoteSessionStore';import * as mobileInteractionModel from '@/session/interactionModel';import {buildAskQuestionProgressSummary,@@ -189,8 +191,6 @@ describe('interactionModel', () => {});expect(presentation.autoReviewUnavailable).toBe(true);- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');- expect(interactionPanelSource).toContain("t('interaction.permission.autoReviewUnavailable')");expect(i18n.t('interaction.permission.autoReviewUnavailable')).not.toBe('interaction.permission.autoReviewUnavailable',);@@ -229,89 +229,16 @@ describe('interactionModel', () => {});});- it('marks the selected ask option with an inverse-filled check for single and multi select', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');-- // 选中态不能只靠 surfaceChip 底色:dark 下它与卡底几乎同色,单选选完看不出- // 选了哪个(线上截图复现)。指示器必须单选/多选都渲染,只在形状上分家。- expect(interactionPanelSource).toContain('isMulti ? styles.optionIndicatorSquare : styles.optionIndicatorRound');- // 选中 = 反色实底 + ctaText 勾,对齐桌面 ask-checkbox(accent-cta-bg 实底)与- // 登录 radio 的「选中反色 + 对勾」体系;不得退回描边勾叠 Square 的弱指示。- expect(interactionPanelSource).toContain('optionIndicatorSelected: {');- expect(interactionPanelSource).toContain('backgroundColor: colors.cta,');- expect(interactionPanelSource).not.toContain('optionCheckboxMark');- });-- it('keeps every Host-owned confirmation read-only in the mobile adapter and panel', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');-+ it('keeps Host-owned decision builders out of the mobile adapter', () => {expect('buildIssueConfirmReviewPresentation' in mobileInteractionModel).toBe(false);expect('buildIssueConfirmDecision' in mobileInteractionModel).toBe(false);expect('normalizeIssueConfirm' in mobileInteractionModel).toBe(false);- expect(interactionPanelSource).toContain(- "kind === 'issue_confirm' || kind === 'rename_sessions_confirm' || kind === 'ghost_grant_confirm'",- );- expect(interactionPanelSource).toContain("t('interaction.panel.desktopConfirmUnsupported')");- expect(interactionPanelSource).not.toContain('buildIssueConfirmReviewPresentation');- });-- it('gives plugin setup requests a cancel exit instead of a dead card', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');-- // 桌面把 plugin_setup 也推给控制端,而配置动作只能在桌面完成。手机侧必须留- // 取消出口:没有出口 + 卡接管输入框 = 会话锁死(线上已复现)。- expect(interactionPanelSource).toContain("if (kind === 'plugin_setup')");- expect(interactionPanelSource).toContain('buildPluginSetupCancelDecision(item.request)');- // testID 与 UnsupportedCard 区分开,UI 测试才能精确定位这张卡的取消按钮(#540 review)。- expect(interactionPanelSource).toContain('interaction.pluginSetup.cancelButton');- expect(interactionPanelSource).not.toContain('interaction.unsupported.cancelButton');- // 未知 kind 仍回退到 UnsupportedCard 的 request 预览,整段一次限行:每行各自- // numberOfLines 会把总高度放大成 6 × 行数。- expect(interactionPanelSource).toContain('const summaryText = contentToPreview(request);');- expect(interactionPanelSource).not.toContain('lines.map((line, index)');- // plugin_setup 移出 UnsupportedCard 后,当初为它加的形参不能留成没人走的分支。- // 钉形参声明与 JSX 传参本身,不做全文匹配——注释里可以照常说明这段历史。- for (const dead of ['summaryLines?:', 'summaryLines={', 'kindLabel?:', 'kindLabel={']) {- expect(interactionPanelSource, dead).not.toContain(dead);- }- // 取消由被控端按 expectedRevision 裁决,不能乐观撤卡(撤了可能其实没取消);- // 但仍要按该 revision 封顶抑制,否则取消前发出的慢快照会把卡写回来。- expect(interactionPanelSource).toContain('optimisticDismiss: false');- expect(interactionPanelSource).toContain('resolvedRevision: cancelDecision.expectedRevision');- expect(interactionPanelSource).toContain('markInteractionRevisionResolved');- // terminal 快照(被控端已 settle)不得给取消按钮:那只会点出一个「看起来成功」- // 的 no-op。门控以共享分类器为单一真相源。- expect(interactionPanelSource).toContain("remoteInteractionHandling(item) === 'cancel-only'");- expect(remoteInteractionHandling({- request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 2, terminal: true },- })).toBe('desktop-only');-- expect(interactionBlocksRemoteComposer({- request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 },- })).toBe(false);- expect(interactionBlocksRemoteComposer({- request: { kind: 'permission', requestId: 'perm-1' },- })).toBe(true);});- it('renders plugin setup as a full read-only status card, not a flat summary', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');-- // 手机端做不了配置动作,这张卡的全部价值在「看懂」:哪个插件、卡在哪一步、- // 为什么失败、回电脑端要做什么。退回扁平摘要就等于把这些信息又丢了。- expect(interactionPanelSource).toContain('function PluginSetupCard(');- expect(interactionPanelSource).toContain('buildRemotePluginSetupPresentation(item.request)');- expect(interactionPanelSource).not.toContain('pluginSetupSummaryLines');- expect(interactionPanelSource).toContain('interaction.pluginSetup.phase.${step.phase}');- expect(interactionPanelSource).toContain('interaction.pluginSetup.error.${step.errorCode}');- expect(interactionPanelSource).toContain('interaction.pluginSetup.action.${step.actionKind}');- // any_of 组要提示「任选其一」,否则用户以为每一步都得做。- expect(interactionPanelSource).toContain("t('interaction.pluginSetup.chooseOne')");- // 已 settle 的收尾帧不该再引导用户「去电脑端完成」。- expect(interactionPanelSource).toContain('presentation.terminal ? null');- // 状态色只用两个语义色 + 灰阶(mobile-design-guide §1)。- expect(interactionPanelSource).toContain('colors.statusReady');- expect(interactionPanelSource).toContain('colors.statusAccent');+ it('keeps plugin setup nonblocking and terminal setup read-only', () => {+ expect(remoteInteractionHandling({ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 2, terminal: true } })).toBe('desktop-only');+ expect(interactionBlocksRemoteComposer({ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 } })).toBe(false);+ expect(interactionBlocksRemoteComposer({ request: { kind: 'permission', requestId: 'perm-1' } })).toBe(true);});it('keeps every plugin setup phase, error code and action kind translated in all locales', async () => {@@ -352,21 +279,6 @@ describe('interactionModel', () => {});it('localizes queue titles and kind labels instead of rendering the shared Chinese defaults', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');-- // 共享层的 title / label 是中文直出;控制端必须按 locale 翻译后再渲染,否则- // 队列头在 en / ja / ko 下仍是中文。- // kind 来自远端、可为任意字符串:必须先经白名单归一再拼 i18next key,- // 否则带 `.` / `__proto__` 的值会参与路径解析。- expect(interactionPanelSource).toContain('interaction.kinds.${localizedInteractionKindKey(itemKind)}.${field}');- expect(interactionPanelSource).toContain('const LOCALIZED_INTERACTION_KINDS = new Set([');- expect(interactionPanelSource).not.toContain('interaction.kinds.${kind}.');- expect(interactionPanelSource).not.toContain('title: selectedQueueItem?.title');- // positionLabel 会被插进队列切换的 accessibility 文案,同样必须翻译,- // 否则读屏在非中文 locale 下念混语。- expect(interactionPanelSource).toContain("t('interaction.panel.queuePositionCurrent')");- expect(interactionPanelSource).toContain("t('interaction.panel.queuePositionNth', { index: index + 1 })");-for (const lang of ['zh-CN', 'zh-TW', 'en', 'ja', 'ko']) {const bundle = JSON.parse(readFileSync(resolve(process.cwd(), `src/i18n/locales/${lang}/interaction.json`), 'utf8'));for (const kind of ['permission', 'ask_user_question', 'plan_review', 'issue_confirm', 'plugin_setup', 'fallback']) {@@ -381,13 +293,19 @@ describe('interactionModel', () => {});it('keys mobile composer blocking off the whole pending set', () => {- const sessionScreenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- // 阻塞判定必须喂整个 pending 集合;喂 activePendingInteraction 会让用户切到- // 一张手机处理不了的卡就绕过仍待处理的权限 / 提问 / 计划卡。- expect(sessionScreenSource).toContain('pendingInteractionsBlockRemoteComposer(pending)');- expect(sessionScreenSource).not.toContain('interactionBlocksRemoteComposer(activePendingInteraction)');-+ const page = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');+ const tree = ts.createSourceFile('session.tsx', page, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'pendingInteractionBlocksComposer') initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!initializer) throw new Error('Missing production pending composer gate');+ const blocks = new Function('pendingInteractionsBlockRemoteComposer', 'pending', 'return (' + initializer.getText(tree) + ')');+ const pending = [{ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 } }, { request: { kind: 'permission', requestId: 'perm-1' } }];+ expect(blocks(pendingInteractionsBlockRemoteComposer, pending)).toBe(true);+ expect(blocks(pendingInteractionsBlockRemoteComposer, pending.slice(0, 1))).toBe(false);expect(pendingInteractionsBlockRemoteComposer([{ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 } },{ request: { kind: 'permission', requestId: 'perm-1' } },@@ -397,24 +315,6 @@ describe('interactionModel', () => {])).toBe(false);});- it('keeps host-only shared-task confirmations as a short desktop-style blocker', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');- const readOnlyStart = interactionPanelSource.indexOf("if (isSharedTaskPeer(deviceId) && !['permission', 'ask_user_question', 'plan_review'].includes(kind)) {");- expect(readOnlyStart).toBeGreaterThan(-1);- const readOnlyEnd = interactionPanelSource.indexOf('return (', interactionPanelSource.indexOf('}', readOnlyStart));- const readOnlySource = interactionPanelSource.slice(readOnlyStart, readOnlyEnd);-- expect(readOnlySource).toContain("t('interaction.panel.readOnlyTitle')");- expect(readOnlySource).toContain("{t('sharedTask.waitingHost')}");- expect(interactionPanelSource).not.toContain('readOnlyReason');- expect(readOnlySource).toContain('JSON.stringify(activeInteraction.request, null, 2)');- expect(readOnlySource).not.toContain('当前请求类型');- expect(readOnlySource).not.toContain('不会回传协作编排决定');- expect(readOnlySource).not.toContain('手机版会保留会话显示');- expect(interactionPanelSource).not.toContain('interaction.readOnlyHint');- expect(interactionPanelSource).not.toContain('hintText: {');- });-it('flags high-risk shell permission requests for mobile confirmation', () => {expect(permissionRiskSummary({kind: 'permission',@@ -699,63 +599,25 @@ describe('interactionModel', () => {} as unknown as PendingInteraction)).toBeNull();});- it('drives the pending collapse from session-level props, not card-local state', () => {- const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');- const sessionScreenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- // 收起入口在队列头,三类卡通用;卡内不得再自持一份 collapsed(两套状态时页面级- // 那份会被卡片 key 变化冲掉,用户刚收起就弹回来)。- expect(interactionPanelSource).toContain('testID="interaction.panel.collapseButton"');- expect(interactionPanelSource).toContain('testID="interaction.panel.collapsedBar"');- expect(interactionPanelSource).not.toContain('setCollapsed(');- expect(interactionPanelSource).not.toContain('interaction.ask.collapseButton');- // 按钮要带可见文字:此前是个没有标签的「—」图标,用户看不出那是「先不答」的出口。- expect(interactionPanelSource).toContain("t('interaction.panel.collapse')");- // 收起态只留一条 bar:仍渲染 PendingTaskHeader 就还是两层结构,消息流照样看不到几行。- const collapsedStart = interactionPanelSource.indexOf('if (collapsed) {');- const collapsedEnd = interactionPanelSource.indexOf('return (', interactionPanelSource.indexOf('}', collapsedStart));- expect(collapsedStart).toBeGreaterThan(0);- expect(interactionPanelSource.slice(collapsedStart, collapsedEnd)).not.toContain('<PendingTaskHeader');- // 状态与回调必须成对:只给一半会得到「显示为收起但点不开」的死界面(#1493 review),- // 所以 collapse 是一个对象 prop,且 collapsed 的判定挂在 canToggleCollapsed 上。- expect(interactionPanelSource).toContain('collapse?: {');- expect(interactionPanelSource).toContain('const collapsed = canToggleCollapsed && isPendingInteractionCollapsed(');- expect(interactionPanelSource).not.toContain('collapsedRequestIds?:');- expect(interactionPanelSource).not.toContain('onToggleCollapsed?(');- // 收起条的摘要与读屏标签都走可断言的 helper(进度从草稿现取)。- expect(interactionPanelSource).toContain('buildCollapsedPendingInteractionPresentation({');- expect(interactionPanelSource).toContain('accessibilityLabel={collapsedBarLabel}');- // 收起入口只给本端能终结的卡,否则队列头切到 plugin_setup 也会冒出「点开回答」。- expect(interactionPanelSource).toContain('canCollapsePendingInteraction(activeInteraction)');-- expect(sessionScreenSource).toContain('collapse={pendingInteractionCollapse}');- expect(sessionScreenSource).not.toContain('collapsedRequestIds={');- expect(sessionScreenSource).toContain('collapsed: activePendingCollapsed');- // 清理必须挂在权威快照上:离线空列表不算「都处理完了」。- expect(sessionScreenSource).toContain('authoritative: pendingInteractionsAuthoritative');- expect(sessionScreenSource).toContain('useSessionPendingInteractionsAuthoritative(sessionId)');- });-- it('models pending authority in the store instead of inferring it from relay status', () => {- const storeSource = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');-- // 权威性是显式状态:全量快照置位,离线 / 设备移除 / clear 复位。- expect(storeSource).toContain('const pendingInteractionsAuthoritative = new Set<string>();');- expect(storeSource).toContain('pendingInteractionsAuthoritative.add(sessionId);');- expect(storeSource).toContain('hasAuthoritativePendingInteractions(sessionId: string): boolean');- expect(storeSource).toContain('export function useSessionPendingInteractionsAuthoritative(');- // markDeviceOffline(经共享清扫 sweepDevicesOffline,批量版 markDevicesOffline- // 同样复用)与 removeDevice 都要撤销权威,否则离线期的空列表会被当权威用。- const sweepStart = storeSource.indexOf('function sweepDevicesOffline(');- const markStart = storeSource.indexOf('markDeviceOffline(deviceId: string): void {');- const offlineEnd = storeSource.indexOf('removeDevice(deviceId: string): void {');- expect(sweepStart).toBeGreaterThan(0);- expect(markStart).toBeGreaterThan(sweepStart);- expect(storeSource.slice(markStart, offlineEnd)).toContain('sweepDevicesOffline([deviceId])');- expect(storeSource.slice(sweepStart, offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');- expect(storeSource.slice(offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');- // []→[] 的权威快照必须能通知出去,否则消费方永远等不到清理时机。- expect(storeSource).toContain('if (streamingChanged || authorityChanged) emit();');+ // Bug #1493: an offline empty projection must never retire a collapsed request.+ it.each(['markDeviceOffline', 'markDevicesOffline', 'removeDevice', 'clear'] as const)('revokes pending authority through %s and publishes a fresh empty snapshot', (action) => {+ remoteSessionStore.clear();+ remoteSessionStore.setDeviceSessions('d1', 'Desktop', [{ id: 's1', name: 'Fixture', status: 'active' } as never]);+ remoteSessionStore.setPendingInteractions('s1', []);+ expect(remoteSessionStore.hasAuthoritativePendingInteractions('s1')).toBe(true);+ if (action === 'clear') remoteSessionStore.clear();+ else if (action === 'markDevicesOffline') remoteSessionStore.markDevicesOffline(['d1']);+ else remoteSessionStore[action]('d1');+ expect(remoteSessionStore.hasAuthoritativePendingInteractions('s1')).toBe(false);+ let notifications = 0;+ const unsubscribe = remoteSessionStore.subscribe(() => { notifications++; });+ try {+ remoteSessionStore.setPendingInteractions('s1', []);+ expect(remoteSessionStore.hasAuthoritativePendingInteractions('s1')).toBe(true);+ expect(notifications).toBe(1);+ remoteSessionStore.setPendingInteractions('s1', []);+ expect(notifications).toBe(1);+ } finally { unsubscribe(); remoteSessionStore.clear(); }});it('translates the collapse affordances in every locale', async () => {diff --git a/apps/mobile/src/__tests__/iosAppDistribution.test.ts b/apps/mobile/src/__tests__/iosAppDistribution.test.tsindex ae4a1e4ed7..9b6fbafca7 100644--- a/apps/mobile/src/__tests__/iosAppDistribution.test.ts+++ b/apps/mobile/src/__tests__/iosAppDistribution.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { beforeEach, describe, expect, it, vi } from 'vitest';const native = vi.hoisted(() => ({@@ -58,49 +56,4 @@ describe('iOS app distribution Expo module', () => {distribution = await import('../../modules/xdt-ios-app-distribution/src/index');await expect(distribution.isIosTestFlightBuild()).resolves.toBe(false);});-- it('keeps StoreKit 2 authoritative and receipt lookup as a fallback', () => {- const swift = readFileSync(- resolve(- process.cwd(),- 'modules/xdt-ios-app-distribution/ios/XdtIosAppDistributionModule.swift',- ),- 'utf8',- );- const moduleConfig = readFileSync(- resolve(process.cwd(), 'modules/xdt-ios-app-distribution/expo-module.config.json'),- 'utf8',- );- const endpointGate = readFileSync(- resolve(process.cwd(), 'src/config/useStartupEndpointGate.ts'),- 'utf8',- );- const startupBundleCheck = readFileSync(- resolve(process.cwd(), 'src/update/useBundleUpdatePrompt.ts'),- 'utf8',- );- const resumeUpdateCheck = readFileSync(- resolve(process.cwd(), 'src/update/useResumeUpdateCheck.ts'),- 'utf8',- );- const settings = readFileSync(- resolve(process.cwd(), 'app/settings.tsx'),- 'utf8',- );-- expect(swift).toContain('try await AppTransaction.shared');- expect(swift).toContain('case .verified(let transaction)');- expect(swift).toContain('case .sandbox:');- expect(swift).toContain('receiptName == "sandboxReceipt"');- expect(moduleConfig).toContain('"platforms": ["apple"]');- expect(moduleConfig).not.toContain('"android"');- // The async StoreKit lookup must complete inside the endpoint gate, before- // REVIEW_MODE is consumed by any update hook or settings screen.- expect(endpointGate).toContain('resolveIsTestFlight: isTestFlightBuild');- // Startup, settings, and resume must all consume the resolved TestFlight- // state before deciding whether the full-package channel is available.- for (const source of [startupBundleCheck, settings, resumeUpdateCheck]) {- expect(source).toContain('isTestFlightBuild: IS_TESTFLIGHT_BUILD');- }- });});diff --git a/apps/mobile/src/__tests__/loginSkinVisual.test.ts b/apps/mobile/src/__tests__/loginSkinVisual.test.tsdeleted file mode 100644index 97a7477a08..0000000000--- a/apps/mobile/src/__tests__/loginSkinVisual.test.ts+++ /dev/null@@ -1,89 +0,0 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--import { loginColors, loginSizes } from '@/theme/tokens';--/**- * PR4a 白底体系视觉行测试(SC-7 slice pr4a:brand-background / login-panel-border /- * wordmark asset / slogan style / splash-brand)。- * 组件树依赖 expo/RN 运行时,node vitest 下沿用仓内既有「读源码接线断言」模式- * (loginScenarioHarness/startupGateCopy 同款);渐变与几何参数由 token/布局引擎- * 纯数据断言兜底。- */-const stageSource = readFileSync(- resolve(process.cwd(), 'src/components/MobileLoginHandoffStage.tsx'),- 'utf8',-);-const controlsSource = readFileSync(- resolve(process.cwd(), 'src/components/LoginSkinControls.tsx'),- 'utf8',-);-const centeredSource = readFileSync(- resolve(process.cwd(), 'src/components/CenteredScreen.tsx'),- 'utf8',-);-const layoutSource = readFileSync(- resolve(process.cwd(), 'app/_layout.tsx'),- 'utf8',-);--describe('loginSkin 白底体系视觉(源码接线 + token 参数)', () => {- it('brand-background:stage 消费主题 surface 纯平底,撤 wave4 双红渐变叠层(对齐 PR#104)', () => {- // 底色 = 主题 surface 纯平底(wave4 改判沿用,不另造字面值),用户 2026-07-22 拍板对齐 PR#104- expect(stageSource).toContain('backgroundColor: colors.login.bgBase');- // 红渐变叠层已移除:组件定义 / token 引用 / SVG 渐变坐标系 / 品牌红字面量全部不再出现- expect(stageSource).not.toContain('LoginBackgroundGradients');- expect(stageSource).not.toContain('loginGradients');- expect(stageSource).not.toContain('gradientUnits');- expect(stageSource).not.toContain('#F70121');- });-- it('brand-background:闸门屏复用同一 full-viewport 宿主(_layout error 分支 stage 化)', () => {- expect(layoutSource).toContain('<MobileLoginHandoffStage>');- expect(layoutSource).toContain('StartupGateBlockedContent');- // 文案 key 化契约保持(startupGateCopy 闸门同源)- expect(layoutSource).toContain("loginText('endpointGateTitle')");- expect(layoutSource).toContain("'endpointGateResetToDev' : 'retry'");- });-- it('login-panel-border:面板 1px panelBorder 描边 + panelBg r36(368:1383)', () => {- expect(controlsSource).toContain('borderColor: colors.login.panelBorder');- expect(controlsSource).toContain('backgroundColor: colors.login.panelBg');- expect(controlsSource).toContain('borderRadius: loginSizes.panelRadius');- expect(loginColors.panelBorder).toBe('#D4D4D4');- expect(loginColors.panelBg).toBe('#FBFBFB');- expect(loginSizes.panelRadius).toBe(36);- // RN 无 inset shadow → borderWidth 1 承载 1px inside 描边- const panelBlock = controlsSource.slice(- controlsSource.indexOf('panel: {'),- controlsSource.indexOf('title: {'),- );- expect(panelBlock).toContain('borderWidth: 1');- });-- it('wordmark:黑红新资产 login-wordmark 接入 stage 且框内 contain 等比适配(368:1381)', () => {- expect(stageSource).toContain("require('../../assets/login/login-wordmark.png')");- expect(stageSource).toContain('resizeMode="contain"');- expect(stageSource).toContain('boxStyle(stage.word)');- // 禁止非等比拉伸:不得出现 stretch- expect(stageSource).not.toContain('"stretch"');- });-- it('slogan:近黑 login-slogan 资产接入 stage 且 contain(368:1394,几何沿旧表)', () => {- expect(stageSource).toContain("require('../../assets/login/login-slogan.png')");- expect(stageSource).toContain('boxStyle(stage.slogan)');- expect(stageSource).toContain("require('../../assets/login/login-hero.png')");- expect(stageSource).toContain('boxStyle(stage.cindy)');- // SLOGAN 近黑 ink token 冻结(资产本体为矢量位图,token 供参数锚定)- expect(loginColors.sloganInk).toBe('#2A2828');- });-- it('splash-brand:CenteredScreen splash 变体复用品牌宿主,红底体系退役', () => {- expect(centeredSource).toContain('MobileLoginHandoffStage');- expect(centeredSource).toContain("testID=\"startup.splash\"");- // 旧红底铺底不再被渲染层消费- expect(centeredSource).not.toContain('colors.brandSplashBackground');- expect(centeredSource).not.toContain('cindy-splash-wordmark-white');- });-});diff --git a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.tsindex 0ba571fa47..49b9e5ce66 100644--- a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts@@ -1,416 +1,85 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { formatCompactTokens } from '@cindy/maker-shared/usage-format';-import { describe, expect, it } from 'vitest';--describe('mobile message actions desktop-first surface', () => {- it('keeps visible message controls compact while preserving touch hit slop', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const sharedSource = readFileSync(resolve(process.cwd(), '../../packages/maker-shared/src/messagePresentation.ts'), 'utf8');-- expect(source).toContain('const MESSAGE_CONTROL_HIT_SLOP = { bottom: 10, left: 10, right: 10, top: 10 };');- expect(source).toContain('const MESSAGE_CONTROL_TOUCH_SIZE = 44;');- expect(source).toContain('buildMessageActionBarPresentation');- expect(sharedSource).toContain("input.canCopy ? 'copy' : null");- expect(sharedSource).toContain("input.canFork ? 'fork' : null");- expect(sharedSource).toContain("input.hasMoreActions ? 'more' : null");- expect(sharedSource).toContain("input.hasTime ? 'time' : null");- expect(sharedSource).toContain("input.hasTurnCost ? 'cost' : null");- expect(source).toContain('<MessageActionSheet');- expect(source).toContain('buildMobileMessageMenu({');- expect(source).toContain("&& (item.message.kind === 'user' || item.message.kind === 'assistant')");- // 运行中删除入口的可见性与 SESSION_RUNNING 识别由- // messageSourceLabelsRender / remoteStatus 的行为测试覆盖。- const screenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- expect(screenSource).toContain('if (isSessionRunningRemoteError(err)) {');- expect(source).toContain('hitSlop={MESSAGE_CONTROL_HIT_SLOP}');- expect(source).toContain('buttonSize={actionBar.buttonSize}');- expect(source).toContain('iconSize={actionBar.iconSize}');- expect(source).toContain("return id === 'copy' || id === 'fork';");- expect(source).toContain('disabled={disabled && !forkBusy}');- expect(source).toContain("busy={id === 'fork' && forkBusy}");- expect(source).toContain("if (id === 'fork' && busy)");- expect(source).toContain("disabledActions={actionBusy ? ['rewind', 'delete'] : undefined}");- expect(source).toContain('testID="message.moreButton"');- expect(source).toContain('{ height: buttonSize, width: buttonSize }');- expect(source).toContain('minHeight: MESSAGE_CONTROL_TOUCH_SIZE');- expect(source).toContain('minWidth: MESSAGE_CONTROL_TOUCH_SIZE');- expect(source).toContain('height: 24');- expect(source).toContain('width: 24');- expect(source).toContain('borderRadius: radius.pill');- expect(sharedSource).toContain('buttonSize: 24');- expect(sharedSource).toContain('iconSize: 14');- expect(source).not.toContain('MESSAGE_CONTROL_ICON_SIZE = 16');- expect(source).not.toContain('messageMetaRow');- expect(source).not.toContain('messageControlRow');- expect(source).not.toContain('testID="message.metaRow"');- expect(source).not.toContain('testID="message.controlRow"');- });-- it('renders user rows carrying a system card as system presentation (no user affordances)', () => {- // silent-stop 自动续跑行(kind='user' + systemCardType,turn 边界所需)必须在- // 渲染层降级为 system 再进 MessageBubble——presentation 的 isUserAligned 是- // `align==='user' || kind==='user'`,不降级会右对齐成用户气泡并挂 fork / rewind- // 操作行(对齐桌面 MessageStream 对该形态提前 return SystemCard,review P2)。- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- expect(source).toContain("? { ...item, message: { ...item.message, kind: 'system' as const } }");- expect(source).toContain(- '<MessageBubble item={hookSourceUserItem ?? systemCardUserItem ?? item} actions={actions} />',- );- });-- it('never hangs the action bar on a system boundary card', () => {- // 系统卡(agent-switch / auto-resume / goal / slash 命令卡)不是发言:桌面- // MessageStream 对 systemCardType 提前 return SystemCard,卡片下方没有任何操作- // 行。手机版曾漏掉这条,跨 Agent 切换的分隔线药丸下多出一行「··· 刚刚」。- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain(- 'const showCompletedActionBar = !shareSelectionActive && mobileMessageShowsActionBar({',- );- expect(source).toContain('hasSystemCard: !!item.message.systemCardType,');- expect(source).toContain('isTurnFinalAssistant: item.message.isTurnFinalAssistant === true,');- // 时间、花费与 More 都必须由该判据统一 gate,不得绕过它单独计算。- expect(source).toContain(- "const relativeTime = showCompletedActionBar ? formatMessageRelativeTime(item.message.createdAt) : '';",- );- expect(source).toContain('const turnCost = showCompletedActionBar && ');- expect(source).not.toContain('const suppressAssistantActions');- });-- it('only exposes the More menu on a completed turn boundary', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain(- 'const canCopyLink = !!(showCompletedActionBar && clientId && actions.onCopyMessageLink);',- );- expect(source).toContain(- 'const canAddToChat = !!(showCompletedActionBar && clientId && actions.onAddMessageToComposer);',- );- expect(source).not.toContain(- 'const canCopyLink = !!(canUseCompletedActions && clientId && actions.onCopyMessageLink);',- );- expect(source).not.toContain(- 'const canAddToChat = !!(canUseCompletedActions && clientId && actions.onAddMessageToComposer);',- );- });-- it('keeps message controls outside the user bubble like the desktop action bar', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const bubbleStart = source.indexOf('const bubble = (');- const messageNodeStart = source.indexOf('const messageNode = (', bubbleStart);- const bubbleSource = source.slice(bubbleStart, messageNodeStart);- const renderSource = source.slice(- messageNodeStart,- source.indexOf('function copyActionLabel', messageNodeStart),- );-- expect(bubbleStart).toBeGreaterThan(-1);- expect(messageNodeStart).toBeGreaterThan(bubbleStart);- expect(bubbleSource).toContain('testID={isUser ? \'message.userBubble\' : \'message.agentBubble\'}');- expect(bubbleSource).not.toContain('testID="message.actionBar"');- expect(renderSource).toContain('styles.messageItem');- expect(renderSource).toContain('isUser ? styles.userMessageItem : styles.agentMessageItem');- // 附件条与气泡都在 action bar 之前(气泡在纯图片消息下可被跳过,但渲染位置不变)- expect(renderSource).toContain(- '{hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}',- );- expect(renderSource.indexOf('? bubble : null')).toBeLessThan(renderSource.indexOf('testID="message.actionBar"'));- });-- it('renders collapsed work groups like the desktop work summary row, not a detail card', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const start = source.indexOf('function WorkGroupCard');- const end = source.indexOf('function FoldablePanel', start);- const workGroupSource = source.slice(start, end);- const expandedBodyStart = workGroupSource.indexOf('{expanded ? (');- const childrenMapStart = workGroupSource.indexOf('{!holdLines && item.children.map((child) => {');-- // 运行中用状态图标,结束后回到桌面同款 Layers 工作摘要图标。- expect(source).toContain('Layers,');- expect(workGroupSource).toContain('const header = presentation.header;');- expect(workGroupSource).toContain('chevronPosition={header.chevronPosition}');- expect(workGroupSource).toContain('chevronSize={header.chevronSize}');- expect(workGroupSource).toContain('title={title}');- expect(workGroupSource).toContain('subtitle={header.subtitle ?? undefined}');- // Work group 受控展开;折叠态不提前构造任何隐藏活动行。运行中只渲染电脑端已投影好的- // 单行活动(deferred.lines),既不读工作明细,也不在本机重新解析工具输入。- expect(workGroupSource).not.toContain('defaultExpanded');- expect(workGroupSource).toContain('controlledExpanded={expanded}');- // 展开后在明细读到之前继续显示这几行,不先清空再重新出现。- expect(workGroupSource).toContain('const lines = isStreaming ? item.deferred?.lines : undefined;');- expect(workGroupSource).toContain("const holdLines = expanded && item.deferred?.awaitingDetails === true && !!lines?.length;");- expect(workGroupSource).toContain('collapsedBody={lineRows ? <Rail layout={layout}>{lineRows}</Rail> : undefined}');- expect(workGroupSource).toContain('{holdLines && lineRows}');- expect(workGroupSource).toContain('<WorkLineRow key={line.key} line={line} onPress={onToggle} />');- expect(workGroupSource).toContain('formatToolRowText(line.descriptor, mobileToolRowWording)');- expect(workGroupSource).not.toContain('summarizeToolUseText');- expect(workGroupSource).toContain('onControlledToggle={onToggle}');- expect(workGroupSource).not.toContain('live-preview-dismissed');- expect(workGroupSource).toContain('? <CompactActivityIndicator color={colors.textTertiary}');- expect(workGroupSource).toContain(': <Layers color={colors.textTertiary}');- expect(workGroupSource).toContain('variant={header.variant}');- expect(workGroupSource).toContain('summaryCount: header.summaryCount');- expect(workGroupSource).toContain('<RenderItemView key={child.key} item={child} actions={actions} />');- expect(workGroupSource).not.toContain('projectRecentMobileWorkActivities');- expect(workGroupSource).toContain('() => (expanded');- expect(workGroupSource).not.toContain('expanded || !isStreaming');- expect(workGroupSource).toContain('const contentLayout = useMemo(() => (expanded');- expect(expandedBodyStart).toBeGreaterThan(-1);- expect(childrenMapStart).toBeGreaterThan(expandedBodyStart);- expect(workGroupSource).toContain('<ExpandedWorkThinkingRow key={child.key} item={child} />');- expect(workGroupSource).toContain('activityProjection?.toolActivitiesByChildKey.get(child.key)');- // thinking / tool 行都固定 28pt,外层不能再给 thinking 子项追加组间距。- expect(source).toContain('workGroupStack: { gap: 0 }');- expect(workGroupSource).not.toContain('subtitle={presentation.subtitle}');- expect(workGroupSource).not.toContain('badges={presentation.badges}');- expect(workGroupSource).not.toContain('badgeCount: presentation.badges.length');- expect(source).not.toContain('testID="message.workGroupToggle"\n variant="card"');- });-- it('keeps plain foldable headers as desktop summary rows, not mobile cards', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const start = source.indexOf('function FoldablePanel');- const end = source.indexOf('function Rail', start);- const foldableSource = source.slice(start, end);-- expect(source).toContain('const FOLDABLE_HEADER_HIT_SLOP = { bottom: 10, left: 4, right: 4, top: 10 };');- expect(foldableSource).toContain("const headerLayoutStyle = variant === 'plain'");- expect(foldableSource).toContain('? styles.foldHeaderPlain');- expect(foldableSource).toContain("hitSlop={variant === 'plain' ? FOLDABLE_HEADER_HIT_SLOP : undefined}");- expect(source).toContain('foldHeaderPlain: {');- expect(source).toContain('gap: 6');- expect(source).toContain('minHeight: 22');- expect(source).toContain('paddingHorizontal: 0');- expect(source).toContain('paddingVertical: 2');- expect(source).toContain("variant === 'plain' && styles.foldTitlePlain");- const plainTitleStart = source.indexOf('foldTitlePlain: {');- const plainTitleEnd = source.indexOf('foldSubtitle:', plainTitleStart);- const plainTitleStyle = source.slice(plainTitleStart, plainTitleEnd);- expect(plainTitleStyle).toContain('color: colors.textSecondary');- expect(plainTitleStyle).toContain('fontSize: typeScale.bodySmall');- expect(plainTitleStyle).toContain('fontWeight: fontWeight.regular');- expect(plainTitleStyle).toContain('lineHeight: lineHeight.bodySmall');- expect(foldableSource).toContain("variant === 'plain'");- expect(foldableSource).toContain('? styles.foldBodyPlain');- });-- it('keeps the load-earlier affordance lighter than message content', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const styleStart = source.indexOf('loadEarlierButton: {');- const styleEnd = source.indexOf('loadEarlierText:', styleStart);- const buttonStyle = source.slice(styleStart, styleEnd);-- expect(buttonStyle).toContain('minHeight: 32');- expect(buttonStyle).toContain('paddingHorizontal: spacing.md');- expect(buttonStyle).not.toContain('borderWidth');- expect(buttonStyle).not.toContain('borderColor');- expect(source).toContain("loadEarlierText: { color: colors.textTertiary");- });-- it('renders collapsed tool groups like the desktop agent action summary row', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const start = source.indexOf('function ToolGroupCard');- const end = source.indexOf('function TodoCard', start);- const toolGroupSource = source.slice(start, end);-- expect(source).toContain('Bot,');- expect(toolGroupSource).toContain('const header = presentation.header;');- expect(toolGroupSource).toContain('chevronPosition={header.chevronPosition}');- expect(toolGroupSource).toContain('chevronSize={header.chevronSize}');- expect(toolGroupSource).toContain('title={header.title}');- expect(toolGroupSource).toContain('subtitle={header.subtitle ?? undefined}');- // 展开态走 blockId 共享记忆,不再传 defaultExpanded(blockId 存在时该值无效)。- expect(toolGroupSource).not.toContain('defaultExpanded');- expect(toolGroupSource).toContain('blockId={item.key}');- // 块头图标:有执行中工具时同槽位换成桌面同款 spinner,否则维持 Bot。- expect(toolGroupSource).toContain('? <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />');- expect(toolGroupSource).toContain(': <Bot color={colors.textTertiary} size={header.iconSize} strokeWidth={iconStroke.regular} />');- expect(toolGroupSource).toContain('variant={header.variant}');- expect(toolGroupSource).toContain('<Rail layout={layout}>');- expect(toolGroupSource).toContain('summaryCount: header.summaryCount');- // 工具行对齐桌面 AgentActionRow:一行摘要,点击就地展开详情;展开态走共享记忆(toolrow- 前缀)。- expect(toolGroupSource).toContain('useFoldableExpandedState(`toolrow-${rowKey ?? tool.key}`, false)');- expect(toolGroupSource).toContain('testID="message.toolRowToggle"');- expect(toolGroupSource).toContain('{showDetails ? (');- // 动作行按 running spinner → failed alert → done check 排序;运行态优先,- // 已结束的真实失败不能误画成成功勾。行头与 thinking 使用同样的 8px inset。- const statusIconStart = source.indexOf('function ToolRowStatusIcon');- const statusIconEnd = source.indexOf('function TodoStatusIcon', statusIconStart);- const statusIconSource = source.slice(statusIconStart, statusIconEnd);- expect(statusIconSource).toContain("status === 'running'");- expect(statusIconSource).toContain('<CompactActivityIndicator');- expect(statusIconSource).toContain('hasError');- expect(statusIconSource).toContain('<CircleAlert');- expect(statusIconSource).toContain('<Check');- expect(source).toContain('<ToolRowStatusIcon hasError={row.hasError} status={row.status} />');- const styleStart = source.indexOf('toolRow: {');- const styleEnd = source.indexOf('toolName:', styleStart);- const actionRowStyles = source.slice(styleStart, styleEnd);- expect(actionRowStyles).not.toContain('borderTopWidth');- expect(actionRowStyles).toContain('paddingHorizontal: spacing.sm');- expect(actionRowStyles).toContain('gap: 6');- // 「查看内容」hint 只在文本结果被截断时显示。- const resultPreviewStart = source.indexOf('function ToolResultPreview');- const resultPreviewEnd = source.indexOf('function MessageContentOpenButton', resultPreviewStart);- const resultPreviewSource = source.slice(resultPreviewStart, resultPreviewEnd);- expect(resultPreviewSource).toContain("payload.kind !== 'text' || clipped");- expect(resultPreviewSource).toContain('{showHint ? <Text style={styles.toolResultHint}>{preview.actionLabel}</Text> : null}');- expect(toolGroupSource).not.toContain('row.signals.map');- expect(toolGroupSource).not.toContain('styles.toolRowSignals');- expect(toolGroupSource).not.toContain('styles.toolRowSignal');- expect(toolGroupSource).not.toContain('subtitle={presentation.subtitle}');- expect(toolGroupSource).not.toContain('badges={presentation.badges}');- expect(toolGroupSource).not.toContain('badgeCount: presentation.badges.length');- expect(toolGroupSource).not.toContain('variant="card"');- });-- it('renders todo cards like the desktop inline checklist, not a separate details sheet', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const start = source.indexOf('function TodoCard');- const end = source.indexOf('function WorkGroupCard', start);- const todoSource = source.slice(start, end);-- expect(source).toContain('ListTodo,');- expect(source).toContain('CircleCheck,');- expect(source).toContain('CircleDashed,');- expect(source).toContain('Circle,');- expect(todoSource).toContain('const header = presentation.header;');- expect(todoSource).toContain('title={header.title}');- expect(todoSource).toContain('subtitle={header.subtitle ?? undefined}');- expect(todoSource).toContain('chevronPosition={header.chevronPosition}');- expect(todoSource).toContain('chevronSize={header.chevronSize}');- expect(todoSource).toContain('defaultExpanded={header.defaultExpanded}');- expect(todoSource).toContain('leadingIcon={<ListTodo color={colors.textPrimary} size={header.iconSize} strokeWidth={iconStroke.regular} />}');- expect(todoSource).toContain('variant={header.variant}');- expect(todoSource).toContain('summaryCount: header.summaryCount');- expect(todoSource).toContain('item.todos.map');- expect(todoSource).toContain('<TodoStatusIcon animated={animated} status={presentation.status} />');- expect(source).toContain('animated={item.isStreaming === true}');- const todoStatusStart = source.indexOf('function TodoStatusIcon');- const todoStatusEnd = source.indexOf('const AGENT_TASK_STATUS_LABEL', todoStatusStart);- const todoStatusSource = source.slice(todoStatusStart, todoStatusEnd);- expect(todoStatusSource).toContain("status === 'in_progress' && animated");- expect(todoStatusSource).toContain('<CompactActivityIndicator');- expect(todoSource).not.toContain('summaryTodos');- expect(todoSource).not.toContain('hiddenCount');- expect(todoSource).not.toContain('todoOpenButton');- expect(todoSource).not.toContain('TodoDetailModal');- expect(todoSource).not.toContain('todoStatusLabel');- expect(source).not.toContain('testID="message.todoSheet"');- expect(source).not.toContain('testID="message.todoOpenButton"');- });-- it('animates only live status icons and freezes them for reduced motion', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const spinnerStart = source.indexOf('function CompactActivityIndicator');- const spinnerEnd = source.indexOf('function ToolRowStatusIcon', spinnerStart);- const spinnerSource = source.slice(spinnerStart, spinnerEnd);- const agentStatusStart = source.indexOf('function AgentTaskStatusIcon');- const agentStatusEnd = source.indexOf('function buildAgentTaskMeta', agentStatusStart);- const agentStatusSource = source.slice(agentStatusStart, agentStatusEnd);-- expect(spinnerSource).toContain('AccessibilityInfo.isReduceMotionEnabled()');- expect(spinnerSource).toContain('AccessibilityInfo.addEventListener(');- expect(spinnerSource).toContain("'reduceMotionChanged'");- expect(spinnerSource).toContain('<Animated.View');- expect(spinnerSource).toContain('duration: 1000');- expect(spinnerSource).toContain('isInteraction: false');- expect(spinnerSource).toContain('useNativeDriver: true');- expect(spinnerSource).toContain("outputRange: ['0deg', '360deg']");- expect(spinnerSource).toContain('<LoaderCircle');- expect(spinnerSource).not.toContain('<CircleDashed');- expect(agentStatusSource).toContain("status === 'running'");- expect(agentStatusSource).toContain('<CompactActivityIndicator');- });-- it('compacts sub-agent token usage with the shared desktop/mobile formatter', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const metaStart = source.indexOf('function buildAgentTaskMeta');- const metaEnd = source.indexOf('\nfunction readAgentTaskToolInput', metaStart);- const metaSource = source.slice(metaStart, metaEnd);-- expect(source).toContain("import { formatCompactTokens } from '@cindy/maker-shared/usage-format';");- expect(metaSource).toContain('`${formatCompactTokens(model.totalTokens)} tokens`');- expect(formatCompactTokens(143_615)).toBe('143.6k');- });-- it('does not keep a hidden badge rendering path in foldable message hierarchy panels', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const sharedSource = readFileSync(resolve(process.cwd(), '../../packages/maker-shared/src/messagePresentation.ts'), 'utf8');- const start = source.indexOf('function FoldablePanel');- const end = source.indexOf('function Rail', start);- const foldableSource = source.slice(start, end);-- expect(source).not.toContain('function MessageBadges');- expect(source).not.toContain('MessagePresentationBadge');- expect(sharedSource).not.toContain('MessagePresentationBadge');- expect(sharedSource).not.toContain('badges:');- expect(sharedSource).not.toContain('signals:');- expect(sharedSource).not.toContain('const badges');- expect(sharedSource).not.toContain('const signals');- expect(foldableSource).not.toContain('badges');- expect(source).not.toContain('messageBadgeRow');- expect(source).not.toContain('messageBadgeText');- });-- it('shows direct thinking/tool rows on open while nested groups keep independent expansion memory', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const renderItemStart = source.indexOf('function RenderItemView');- const renderItemEnd = source.indexOf('function EmptyMessages', renderItemStart);- const renderItemSource = source.slice(renderItemStart, renderItemEnd);- const thinkingStart = source.indexOf('function ThinkingCard');- const thinkingEnd = source.indexOf('function ToolGroupCard', thinkingStart);- const thinkingSource = source.slice(thinkingStart, thinkingEnd);- const workGroupStart = source.indexOf('function WorkGroupCard');- const workGroupEnd = source.indexOf('function FoldablePanel', workGroupStart);- const workGroupSource = source.slice(workGroupStart, workGroupEnd);- const foldableStart = source.indexOf('function FoldablePanel');- const foldableEnd = source.indexOf('function Rail', foldableStart);- const foldableSource = source.slice(foldableStart, foldableEnd);-- // 当前动作组展开后直接读思考/工具;完成态外层里的嵌套动作组仍通过 RenderItemView 保持第二级折叠。- expect(source).not.toContain('expandByDefault');- expect(workGroupSource).toContain("if (child.type === 'thinking')");- expect(workGroupSource).toContain('<ExpandedWorkThinkingRow key={child.key} item={child} />');- expect(workGroupSource).toContain("if (child.type === 'tool_group')");- expect(workGroupSource).toContain('activityProjection?.toolActivitiesByChildKey.get(child.key)');- expect(workGroupSource).toContain('<RenderItemView key={child.key} item={child} actions={actions} />');- // 展开态走共享进程内记忆,跨虚拟化重挂/切会话/重分组稳定。- expect(workGroupSource).toContain('useFoldableExpandedState(item.key, false)');- expect(foldableSource).toContain('useFoldableExpandedState(blockId, defaultExpanded)');- expect(thinkingSource).toContain('blockId={item.key}');- expect(renderItemSource).toContain('<ToolGroupCard item={item} actions={actions} />');- // 思考卡接收会话流式信号;界面只显示到秒,不需要半秒级刷新。- expect(renderItemSource).toContain('isSessionStreaming={actions.isSessionStreaming === true}');- expect(source).toContain('setInterval(() => setNow(Date.now()), 1_000)');- });-- it('does not render user or assistant role labels inside message bubbles', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const sharedSource = readFileSync(resolve(process.cwd(), '../../packages/maker-shared/src/messagePresentation.ts'), 'utf8');- const bubbleStart = source.indexOf('function MessageBubble');- const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);- const bubbleSource = source.slice(bubbleStart, bubbleEnd);-- expect(bubbleSource).toContain('summarizeMessageBubblePresentation');- expect(source).not.toContain('label: item.message.label');- expect(sharedSource).not.toContain('roleLabel:');- expect(sharedSource).not.toContain('displayMessageRoleLabel');- expect(bubbleSource).not.toContain('presentation.roleLabel');- expect(bubbleSource).not.toContain('message.roleLabel');- expect(bubbleSource).not.toContain('message.authorLabel');- expect(bubbleSource).not.toContain('你</Text>');- expect(bubbleSource).not.toContain('XDMaker</Text>');- });-- it('renders compact reasoning with shared strong/code parsing and one-line expansion', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- expect(source).toContain("tokenizeThinkingText(content)");- expect(source).toContain("token.kind === 'strong'");- expect(source).toContain("token.kind === 'code'");- expect(source).toContain('numberOfLines={expanded ? undefined : 1}');- expect(source).toContain('testID="message.workThinkingToggle"');- expect(source).toContain('onTextLayout={(event) => setMeasuredLineCount(event.nativeEvent.lines.length)}');+// @vitest-environment jsdom+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useTranslation } from 'react-i18next';+import { i18n } from '@/i18n';+import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';+import { useFoldableExpandedState, __test_internals } from '@/session/expandedBlockMemory';+import { summarizeWorkGroupPresentation } from '@/session/messagePresentation';+import { buildMessageHierarchyLayout } from '@/session/messageHierarchyLayout';+import { buildMessageContentLayout } from '@/session/messageContentLayout';+import { iconSize, iconStroke, lightColors } from '@/theme/tokens';+import { executeRenderer, rendererFunction, rendererSource } from './fixtures/messageRendererComponents';++// §3.2: actual component bodies, React hooks and shared folding memory protect+// lazy work-detail reads, retained pending lines and generic tool input fallback.+// The prior source/geometry scans never exercised these visible transitions.+function View({ children, testID, onPress, disabled }: any) {+ return React.createElement(onPress ? 'button' : 'div', { 'data-testid': testID, onClick: onPress, disabled }, children);+}+const leaf = () => null;+const child = vi.fn(({ item }: any) => React.createElement('span', null, item.key));+const source = ['ToolActionRow', 'WorkGroupCard'].map(name => rendererFunction(name).getText(rendererSource)).join(String.fromCharCode(10));+const components = executeRenderer<Record<string, React.ComponentType<any>>>(source + '; return { ToolActionRow, WorkGroupCard };', {+ useState: React.useState, useRef: React.useRef, useEffect: React.useEffect, useMemo: React.useMemo,+ useTranslation, useFoldableExpandedState, summarizeWorkGroupPresentation,+ mobilePresentationLocalizer, buildMessageHierarchyLayout, buildMessageContentLayout,+ View, Text: View, Pressable: View, useTheme: () => ({ colors: lightColors }),+ useThemedStyles: () => ({}), makeStyles: leaf, iconSize, iconStroke,+ ChevronDown: leaf, ChevronRight: leaf, Layers: leaf, ToolRowStatusIcon: leaf,+ CompactActivityIndicator: leaf, WorkGroupElapsed: leaf, PluginInvocationHeader: leaf,+ Rail: View, RenderItemView: child, ExpandedWorkThinkingRow: child,+ projectMobileWorkActivities: () => ({ isPureExploration: false, toolActivitiesByChildKey: new Map() }),+ FoldablePanel: ({ children, collapsedBody, controlledExpanded, onControlledToggle, testID }: any) =>+ React.createElement('div', null,+ React.createElement('button', { 'data-testid': testID, onClick: onControlledToggle }, 'toggle'),+ controlledExpanded ? children : collapsedBody),+ WorkLineRow: ({ line, onPress }: any) => React.createElement('button', { onClick: onPress }, line.text),+});+function mount(name: string, props: any) {+ const host = document.createElement('div'), root = createRoot(host);+ const update = (next: any) => act(() => root.render(React.createElement(components[name], next)));+ update(props);+ return { host, update, unmount: () => act(() => root.unmount()) };+}+beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ __test_internals.reset(); child.mockClear();+ await i18n.changeLanguage('zh-CN');+});+describe('message detail lifecycle', () => {+ it('keeps folded work lazy and retains projected lines until expanded details arrive', () => {+ const setVisible = vi.fn();+ const item: any = { type: 'work_group', key: 'work', children: [{ type: 'message', key: 'detail' }],+ isStreaming: true, durationMs: 0, deferred: { owner: 'host', key: 'work', setVisible,+ awaitingDetails: true, lines: [{ key: 'line', kind: 'thinking', text: 'Reading' }] } };+ const h = mount('WorkGroupCard', { item, actions: {} });+ try {+ expect(child).not.toHaveBeenCalled(); expect(h.host.textContent).toContain('Reading');+ act(() => h.host.querySelector('button')!.click());+ expect(setVisible).toHaveBeenCalledWith(true, false);+ expect(h.host.textContent).toContain('Reading'); expect(child).not.toHaveBeenCalled();+ h.update({ item: { ...item, deferred: { ...item.deferred, awaitingDetails: false } }, actions: {} });+ expect(h.host.textContent).toContain('detail'); expect(h.host.textContent).not.toContain('Reading');+ } finally { h.unmount(); }+ expect(setVisible).toHaveBeenLastCalledWith(false, false);+ });++ it('reveals generic tool input when structured detail is absent and remembers row folding', () => {+ const props = { actions: {}, contentLayout: {}, row: { label: 'Custom tool', status: 'done', hasError: false },+ tool: { key: 'custom', body: 'original input summary' } };+ let h = mount('ToolActionRow', props);+ try {+ expect(h.host.textContent).not.toContain('original input summary');+ act(() => h.host.querySelector('button')!.click());+ expect(h.host.textContent).toContain('original input summary');+ h.update({ ...props, row: { ...props.row, detail: 'structured input' } });+ expect(h.host.textContent).toContain('structured input');+ expect(h.host.textContent).not.toContain('original input summary');+ } finally { h.unmount(); }+ h = mount('ToolActionRow', props);+ try { expect(h.host.textContent).toContain('original input summary'); } finally { h.unmount(); }});});diff --git a/apps/mobile/src/__tests__/messageActionMenu.test.ts b/apps/mobile/src/__tests__/messageActionMenu.test.tsindex e632e55c60..0bb8626d70 100644--- a/apps/mobile/src/__tests__/messageActionMenu.test.ts+++ b/apps/mobile/src/__tests__/messageActionMenu.test.ts@@ -1,10 +1,38 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { beforeAll, describe, expect, it } from 'vitest';+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { useTranslation } from 'react-i18next';+import ts from 'typescript';+import { beforeAll, describe, expect, it, vi } from 'vitest';import { i18n } from '@/i18n';import { buildMobileMessageMenu } from '@/session/messageActionMenu';import { iconSize } from '@/theme/tokens';+// Run the actual component hooks and callbacks; only native sheet animation is+// injected. A click must close first, then dispatch once on the native onClosed.+const sheetSource = ts.createSourceFile('MessageActionSheet.tsx', readFileSync(resolve(process.cwd(), 'src/session/MessageActionSheet.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const sheetFunction = sheetSource.statements.find((node): node is ts.FunctionDeclaration => ts.isFunctionDeclaration(node) && node.name?.text === 'MessageActionSheet');+if (!sheetFunction) throw new Error('MessageActionSheet production component is missing');+const sheet = { props: null as any };+const native = ({ children, testID, onPress, disabled }: any) => React.createElement(onPress ? 'button' : 'div', { 'data-testid': testID, onClick: onPress, disabled }, children);+const icon = () => null;+function executeSheet(code: string, bindings: Record<string, unknown>): React.ComponentType<any> {+ const compiled = ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;+ const globals = { React, ...bindings };+ return new Function(...Object.keys(globals), compiled)(...Object.values(globals));+}+const ActionSheet = executeSheet(sheetFunction.getText(sheetSource).replace('export function', 'function') + '; return MessageActionSheet;', {+ useCallback: React.useCallback, useEffect: React.useEffect, useRef: React.useRef, useTranslation,+ View: native, Text: native, Pressable: native,+ useThemedStyles: () => ({}), makeStyles: icon, useTheme: () => ({ colors: {} }),+ useSafeAreaInsets: () => ({ bottom: 0 }), spacing: { md: 16 }, iconSize, iconStroke: { regular: 1.5 },+ BlurBackdrop: icon, ACTION_ICONS: { 'add-to-chat': icon, 'copy-link': icon, rewind: icon, delete: icon },+ SheetModal: (props: any) => { sheet.props = props; return React.createElement('div', null, props.children); },+});+// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。beforeAll(async () => {await i18n.changeLanguage('zh-CN');@@ -48,12 +76,26 @@ describe('mobile message action menu', () => {}});- it('reuses the shared sheet lifecycle and dispatches a choice after close', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageActionSheet.tsx'), 'utf8');- expect(source).toContain('<SheetModal');- expect(source).toContain('onClosed={handleClosed}');- expect(source).toContain('pendingActionRef.current = action');- expect(source).not.toContain('<Modal');- expect(source).not.toContain('Animated.timing');+ it('dispatches once after closing and cancels a stale choice when reopened', () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ const host = document.createElement('div'), root = createRoot(host);+ const onAction = vi.fn(), onClose = vi.fn();+ const props = { items: buildMobileMessageMenu({ canAddToChat: false, canCopyLink: false, canDelete: true, canRewind: true }), onAction, onClose };+ const update = (visible: boolean) => act(() => root.render(React.createElement(ActionSheet, { ...props, visible })));+ try {+ update(true);+ act(() => host.querySelector<HTMLButtonElement>('[data-testid="message.actions.delete"]')!.click());+ expect(onClose).toHaveBeenCalledTimes(1); expect(onAction).not.toHaveBeenCalled();+ update(false); act(() => sheet.props.onClosed()); act(() => sheet.props.onClosed());+ expect(onAction).toHaveBeenCalledExactlyOnceWith('delete');+ onAction.mockClear(); update(true);+ act(() => host.querySelector<HTMLButtonElement>('[data-testid="message.actions.rewind"]')!.click());+ update(false); update(true); update(false); act(() => sheet.props.onClosed());+ expect(onAction).not.toHaveBeenCalled();+ update(true);+ act(() => host.querySelector<HTMLButtonElement>('[data-testid="message.actions.delete"]')!.click());+ act(() => sheet.props.onRequestClose()); update(false); act(() => sheet.props.onClosed());+ expect(onAction).not.toHaveBeenCalled();+ } finally { act(() => root.unmount()); }});});diff --git a/apps/mobile/src/__tests__/messageContentDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageContentDesktopFirst.test.tsdeleted file mode 100644index 3081edcafc..0000000000--- a/apps/mobile/src/__tests__/messageContentDesktopFirst.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { existsSync, readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--describe('mobile message content desktop-first surface', () => {- it('uses desktop-matching file icons instead of text badges for file chips', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- // The desktop user-message file chip lives in UserAttachmentChip.tsx (shared with group chat).- const desktopChat = resolve(process.cwd(), '../../apps/desktop/src/renderer/components/chat');- const desktopSource = ['UserMessage.tsx', 'UserAttachmentChip.tsx']- .map((file) => resolve(desktopChat, file))- .filter((file) => existsSync(file))- .map((file) => readFileSync(file, 'utf8'))- .join('\n');- const layoutSource = readFileSync(resolve(process.cwd(), 'src/session/messageContentLayout.ts'), 'utf8');- const fileChipStart = source.indexOf('function FileChip');- const fileChipEnd = source.indexOf('function DiffPreview', fileChipStart);- const fileChipSource = source.slice(fileChipStart, fileChipEnd);-- expect(desktopSource).toContain("'h-7 px-2.5 py-1.5'");- expect(desktopSource).toContain('<span className="truncate">{file.name}</span>');- expect(desktopSource).toContain('<FileTypeIcon name={file.name}');- expect(fileChipSource).toContain('<FileTypeIcon name={name || path} color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />');- expect(source).toContain('style={[styles.fileIconFrame, { width: layout.fileChipIconWidth }]}');- expect(fileChipSource).toContain('<Text style={styles.fileName} numberOfLines={1}>{preview.title}</Text>');- expect(fileChipSource).not.toContain('preview.detail');- expect(layoutSource).toContain('fileChipMinHeight: 32');- expect(source).not.toContain('function fileChipLabel');- expect(source).not.toContain("return 'FILE';");- expect(source).not.toContain('<Text style={[styles.fileIcon');- expect(source).not.toContain('filePath: { color: colors.textTertiary');- });-- it('uses icon-only payload header actions like desktop lightboxes', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain('ExternalLink,');- expect(source).toContain('X,');- expect(source).toContain('<Copy color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />');- expect(source).toContain('<ExternalLink color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />');- expect(source).toContain('<X color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />');- expect(source).not.toContain('function payloadCopyLabel');- expect(source).not.toContain('payloadHeaderButtonText');- expect(source).not.toContain('payloadGalleryButtonText');- expect(source).not.toContain('<Text style={styles.payloadHeaderButtonText}>打开</Text>');- expect(source).not.toContain('<Text style={styles.payloadGalleryButtonText}>上一张</Text>');- expect(source).not.toContain('<Text style={styles.payloadGalleryButtonText}>下一张</Text>');- });-- it('titles payload detail panels by user-facing content instead of debug labels', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const mediaFlow = readFileSync(resolve(process.cwd(), 'e2e/maestro/media_smoke.yaml'), 'utf8');- const mediaExpoGoFlow = readFileSync(resolve(process.cwd(), 'e2e/maestro/media_smoke_expo_go.yaml'), 'utf8');- const fileFlow = readFileSync(resolve(process.cwd(), 'e2e/maestro/file_preview.yaml'), 'utf8');- const visualPayloadFlow = readFileSync(resolve(process.cwd(), 'e2e/maestro/visual_session_payload.yaml'), 'utf8');- const flowSmokeSource = readFileSync(resolve(process.cwd(), 'scripts/maestro-flow-smoke.mjs'), 'utf8');- const modalStart = source.indexOf('function MessagePayloadModal');- const modalEnd = source.indexOf('type RemoteMediaState', modalStart);- const modalSource = source.slice(modalStart, modalEnd);- const e2eSource = [- mediaFlow,- mediaExpoGoFlow,- fileFlow,- visualPayloadFlow,- flowSmokeSource,- ].join('\n');-- expect(modalSource).toContain('testID="message.payloadViewerHeader"');- expect(modalSource).toContain('<Text style={styles.payloadTitle} numberOfLines={headerLayout.titleNumberOfLines}>{payloadSummary?.title ?? \'\'}</Text>');- expect(modalSource).toContain('testID="message.payloadSubtitle"');- expect(source).not.toContain('styles.payloadTitleMetaRow');- expect(source).not.toContain('payloadTitleMetaRow: {');- expect(source).not.toContain('styles.payloadEyebrow');- expect(source).not.toContain('payloadEyebrow: {');- expect(source).not.toContain('PAYLOAD');- expect(source).not.toContain('message.payloadKind');- expect(source).not.toContain('message.payloadSeverity');- expect(source).not.toContain('payloadKindPill');- expect(source).not.toContain('payloadSeverityPill');- expect(source).not.toContain('function payloadSeverityLabel');- expect(e2eSource).not.toContain('message.payloadKind');- expect(e2eSource).not.toContain('message.payloadSeverity');- // 图片流已改走全屏 ImageLightbox(无标题/正文),烟测断言 lightbox 出现与可关闭- expect(mediaFlow).toContain('visible: "Mock image fixture"');- expect(mediaFlow).toContain('id: "message.imageLightbox"');- expect(mediaExpoGoFlow).toContain('id: "message.imageLightbox"');- expect(fileFlow).toContain('assertVisible: "mock-spec.md"');- expect(visualPayloadFlow).toContain('text: "Visual payload fixture"');- expect(visualPayloadFlow).toContain('id: "message.imageLightbox"');- });-- it('does not pin desktop-only media follow-up guidance in the main message stream', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const layoutSource = readFileSync(resolve(process.cwd(), 'src/session/messageContentLayout.ts'), 'utf8');-- expect(source).toContain('function ToolMediaBlock');- expect(source).toContain('buildMediaPayload(entry, entry.title || mediaLabel(entry))');- expect(source).not.toContain('function ToolMediaActionsNotice');- expect(source).not.toContain('message.mediaActionsNotice');- expect(source).not.toContain('桌面操作');- expect(source).not.toContain('手机版暂不触发');- expect(source).not.toContain('mediaActionButtonLabel');- expect(layoutSource).not.toContain('mediaActionChipMinHeight');- });-- it('keeps generic tool input summaries visible when structured row detail is absent', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain('row.detail || tool.body');- expect(source).toContain('{row.detail ?? tool.body}');- });-- it('keeps mobile markdown typography close to the desktop message hierarchy', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const tokenSource = readFileSync(resolve(process.cwd(), 'src/theme/tokens.ts'), 'utf8');-- expect(tokenSource).toContain('bodySmall: 15');- expect(source).toContain('messageText: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge }');- // 行内代码、代码块、表格、待办四处保持 15 号(bodySmall,原 code 档)。- for (const name of ['markdownInlineCode', 'markdownCodeText', 'markdownTableCell', 'todoText']) {- const block = source.match(new RegExp(`\\n\\s*${name}: \\{[^{}]*\\}`))?.[0] ?? '';- expect(block, name).toContain('fontSize: typeScale.bodySmall');- }- });-- it('keeps message content readable on iPad and phone landscape', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(source).toContain('buildMobileReadableViewportLayout');- expect(source).toContain('viewportLayout.contentWidth');- expect(source).toContain('viewportLayout.wideViewport && styles.messagesWide');- expect(source).toContain('viewportLayout.wideViewport && { maxWidth: viewportLayout.contentMaxWidth }');- });-});diff --git a/apps/mobile/src/__tests__/messageImageHandoff.test.tsx b/apps/mobile/src/__tests__/messageImageHandoff.test.tsxindex 31fb499fba..122852eafa 100644--- a/apps/mobile/src/__tests__/messageImageHandoff.test.tsx+++ b/apps/mobile/src/__tests__/messageImageHandoff.test.tsx@@ -179,7 +179,7 @@ describe('image frame continuity', () => {ts.forEachChild(node, visit);}visit(file);- expect(properties).toHaveLength(selected.length);+ if (properties.length !== selected.length) throw new Error('Missing production row geometry');return new Function('spacing', 'MOBILE_MESSAGE_LIST_BOTTOM_PADDING', `return ({${properties.join(',')}});`)(spacing, 0);}const pending = styles(pendingSource, ['rowWrap', 'bubbleRow', 'content', 'attachmentStrip']);diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.tssimilarity index 68%rename from apps/mobile/src/__tests__/messageListVirtualization.test.tsrename to apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.tsindex af0482a53d..ae607d0518 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts@@ -2,19 +2,18 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';-// 消息列表容器契约:LegendList(替代 FlatList —— 滚动 mount 卡顿的实测解,见 listperf profiling:-// windowSize=21 的大挂载树 p95≈167ms/jank46,换 LegendList 小预渲窗口后 p95≈20ms/jank4)。-// 关键 prop 不可回退:估高 + 小 drawDistance(挂载集小)+ iOS 原生 / Android 应用层 prepend 锚定。-describe('mobile message list container', () => {- it('uses LegendList virtualization with platform-scoped history anchoring', () => {+// Guard: JS/native lifecycle contracts for Fabric cell ownership, asynchronous+// MVCP/gesture handoff, native reveal and UITextView selection. Node component+// tests cannot exercise the native commit/measurement or system selection menu.+// Regressions cause blank historical pages, stale recycled media or lost Copy.+// Entry/reopening/tail controller behavior stays in messageEntryPositioning,+// messageReadingRestore and messageTailFollower unit tests. Pure geometry and+// duplicated controller source checks are deliberately not retained here.+describe('native message lifecycle contracts', () => {+it('uses LegendList virtualization with platform-scoped history anchoring', () => {const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');const perfHarness = readFileSync(resolve(process.cwd(), 'app/listperf.tsx'), 'utf8');- // 已完全迁出 FlatList:不再出现 FlatList 容器,也不再有其虚拟化专有 prop。- expect(source).not.toContain('<FlatList');- expect(source).not.toContain('windowSize={');- expect(source).not.toContain('getItemLayout={');-const listStart = source.search(/<LegendList\s/);expect(listStart).toBeGreaterThan(-1);const listEnd = source.indexOf(' />', listStart);@@ -22,8 +21,6 @@ describe('mobile message list container', () => {const listSource = source.slice(listStart, listEnd);// 估高 + 小预渲窗口:挂载集小、mount 帧压进一帧(不可退回大挂载树)。- expect(listSource).toContain('estimatedItemSize={MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE}');- expect(listSource).toContain('drawDistance={MOBILE_MESSAGE_DRAW_DISTANCE}');// 与 main 一致,完整历史从首次挂载起就在列表中;不可退回只挂末尾几条的业务尾窗,// 否则短尾窗未撑满首屏时 Android 无法拖动历史。expect(listSource).toContain('data={listData}');@@ -70,15 +67,6 @@ describe('mobile message list container', () => {expect(source).toContain('useRecyclingState');// 可见性必须由 cell 自己订阅。把可见 key 集合放进 React Context 会在每个// onViewableItemsChanged 回调里广播给所有已挂载长消息,快滑时造成整窗重渲染、GC 和白屏。- expect(source).not.toContain('MessageListVisibleKeysContext');- expect(source).not.toContain('visibleMessageKeys');- expect(source).toContain("const MESSAGE_LIST_VIEWABILITY_CONFIG_ID = 'message-heavy-content';");- expect(source).toContain('id: MESSAGE_LIST_VIEWABILITY_CONFIG_ID');- expect(source).toContain('useMessageListItemVisible(item.key)');- expect(source).toContain('useMemo(() => new MessageListVisibility(), [scrollResetKey])');- expect(source).toContain('messageListVisibility.update(info.viewableItems)');- expect(source).toContain('maxTextRunInlineFragments: ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS');- expect(listSource).not.toContain('onFirstVisibleItemChanged');// Companion receipts observe visible rows through a ref, without broadcasting cell visibility.// Both modes publish visibility, but only companion chats acknowledge read receipts.expect(listSource).toContain('onViewableItemsChanged={handleViewableItemsChanged}');@@ -224,52 +212,18 @@ describe('mobile message list container', () => {expect(focusEffectSource).toContain('lastAutoLoadEarlierKeyRef.current = null');});- it('bounds the hidden initial correction while keeping full history mounted', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- expect(source).toContain('programmaticScrollInFlight: programmaticScrollInFlightRef.current');- expect(source).toContain('createMobileTailFollower({');- expect(source).not.toContain('initialAnchorVerifyFrameRef');- expect(source).toContain('scrollToEndProgrammatically(false)');- // mVCP 只对 size 常开;流式 resize 仍需记 settle 安静窗,跟随 verifier 不能只依赖- // readingOlderRef 判断是否等待。- expect(source).toContain('mvcpSettleAtRef.current = mobileMvcpSettleDeadline(');- expect(source).toContain('markMobileMvcpSettle();');- expect(source).toContain('mobileMessageListKeysSignature(itemKeys)');- expect(source).toContain('[itemKeysSignature, markMobileMvcpSettle]');- expect(source).not.toContain('[itemKeys, markMobileMvcpSettle]');- expect(source).toContain('layoutSettleAt: mvcpSettleAtRef.current');- expect(source).toContain('const nextStableFrames = settled ? stableFrames + 1 : 0;');-- expect(source).toContain('key={scrollResetKey}');- expect(source).not.toContain('tailWindowAnchor');- expect(source).not.toContain('previousUserButton');- // 首次校正仍会命令式落底,但 opacity 揭示必须立即交给 UI-thread native driver;- // 复杂消息占满 JS 时不能把 300ms 隐藏窗拖成长达数秒的白屏。- expect(source).not.toContain('onLoad={handleListLoad}');- expect(source).toContain('const [listRevealed, setListRevealed] = useState(false);');- expect(source).toContain('setListRevealed(true);');- expect(source).toContain('const initialRevealProgress = useMemo(');- expect(source).toContain('const initialRevealOpacity = listRevealed ? 1 : initialRevealProgress;');- expect(source).toContain('<Animated.View style={[styles.messageList, { opacity: initialRevealOpacity }]}>');- expect(source).toContain('const MOBILE_INITIAL_REVEAL_MAX_MS = 300;');- expect(source).not.toContain('MOBILE_INITIAL_REVEAL_FADE_MS');- expect(source).toContain('onSettled: revealPositionedHistory');- expect(source).toContain('tailFollowerRef.current = null;');- const initialAnchorEffectStart = source.indexOf('// 首次落底:完整历史已经在列表里');- const initialAnchorEffectEnd = source.indexOf('// 会话切换(scrollResetKey)', initialAnchorEffectStart);- const initialAnchorEffectSource = source.slice(initialAnchorEffectStart, initialAnchorEffectEnd);- expect(initialAnchorEffectSource).toContain('Animated.timing(initialRevealProgress, {');- expect(initialAnchorEffectSource).toContain('useNativeDriver: true');- expect(initialAnchorEffectSource).toContain('easing: Easing.step1');- expect(initialAnchorEffectSource).not.toContain('const verify =');- expect(initialAnchorEffectSource).not.toContain('setTimeout(');- expect(initialAnchorEffectSource).toContain('scrollToEndProgrammatically(false);');- expect(initialAnchorEffectSource).not.toContain('requestAnimationFrame(');- expect(source).not.toContain('initialRevealTimerRef');- expect(source).not.toContain('messageListSettling');- });+it('hands the bounded initial reveal to the native animation driver', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const start = source.indexOf('// 首次落底:完整历史已经在列表里');+ const end = source.indexOf('// 会话切换(scrollResetKey)', start);+ const reveal = source.slice(start, end);+ expect(reveal).toContain('Animated.timing(initialRevealProgress, {');+ expect(reveal).toContain('useNativeDriver: true');+ expect(reveal).toContain('easing: Easing.step1');+ expect(reveal).not.toContain('setTimeout(');+});- it('resets identity-bound row state before a recycled cell displays another item', () => {+it('resets identity-bound row state before a recycled cell displays another item', () => {const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');const expandedStateSource = readFileSync(resolve(process.cwd(), 'src/session/expandedBlockMemory.ts'),@@ -306,72 +260,7 @@ describe('mobile message list container', () => {expect(expandedStateSource).toContain('blockId ? store.subscribe(listener) : () => {}');});- it('uses the same explicit action for sending and jumping to the latest message', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const effectStart = source.indexOf('// Sending and the jump button');- const effectEnd = source.indexOf('// 自动加载更早', effectStart);- expect(source.slice(effectStart, effectEnd)).toContain('scrollToBottom();');- const jump = source.slice(source.indexOf('const scrollToBottom'), source.indexOf('// A retained list must not replay requests'));- expect(jump.indexOf('userScrollForOlderRef.current = false')).toBeLessThan(- jump.indexOf("scrollToEndProgrammatically(true, 'explicit')"),- );- });-- it('routes manual jump-to-latest through the controller that owns seek and verification', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const callbackStart = source.indexOf('const scrollToBottom = useCallback');- const callbackEnd = source.indexOf('// A retained list must not replay requests', callbackStart);- const callbackSource = source.slice(callbackStart, callbackEnd);- const scrollAt = callbackSource.indexOf("scrollToEndProgrammatically(true, 'explicit');");-- expect(callbackStart).toBeGreaterThan(-1);- expect(callbackEnd).toBeGreaterThan(callbackStart);- expect(scrollAt).toBeGreaterThan(-1);- expect(callbackSource).not.toContain('runStickToLatestVerify();');- expect(callbackSource).toContain(- '}, [cancelHistoryPrependTransaction, scrollToEndProgrammatically]);',- );- });-- it('passes native geometry and animation ownership into the tail controller', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const adapter = source.slice(source.indexOf('const getTailFollower'), source.indexOf('const scrollToEndProgrammatically'));- expect(adapter).toContain('metrics: scrollMetricsRef.current');- expect(adapter).toContain('programmaticAnimatedScrollInFlightRef.current');- expect(adapter).toContain('programmaticScrollSettleAtRef.current');- expect(adapter).toContain('scrollToOffset({ animated: false, offset })');- expect(source).not.toContain('followVerifyFrameRef');- expect(source).not.toContain('followEndPinRecoveryTimerRef');- });-- it('clears stale history intent when a manual downward scroll re-pins at the bottom', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const scrollStart = source.indexOf('// 近底/跟随态迁移');- const scrollEnd = source.indexOf('// 用户开始拖动', scrollStart);- const scrollSource = source.slice(scrollStart, scrollEnd);-- expect(scrollStart).toBeGreaterThan(-1);- expect(scrollEnd).toBeGreaterThan(scrollStart);- expect(scrollSource).toContain('const wasNearBottom = nearBottomRef.current');- expect(scrollSource).toContain('if (!wasNearBottom && nearBottom && scrollDelta > 0)');- expect(scrollSource).toContain('userScrollForOlderRef.current = false');- });-- it('keeps follow verification enabled for a dead-zone drag that never actually unpins', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const verifyStart = source.indexOf('const getTailFollower');- const verifyEnd = source.indexOf('const scrollToEndProgrammatically', verifyStart);- const verifySource = source.slice(verifyStart, verifyEnd);-- expect(verifyStart).toBeGreaterThan(-1);- expect(verifyEnd).toBeGreaterThan(verifyStart);- expect(verifySource).toContain('stickToLatest: nearBottomRef.current');- expect(verifySource).not.toContain(- 'stickToLatest: nearBottomRef.current && !userScrollForOlderRef.current',- );- });-- it('measures every mounted shareable message, including expanded group children', () => {+it('measures every mounted shareable message, including expanded group children', () => {const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');const readerStart = source.indexOf('const readActuallyVisibleShareableMessageIds');const readerEnd = source.indexOf('useEffect(() => {', readerStart);@@ -386,4 +275,91 @@ describe('mobile message list container', () => {'itemVisiblePercentThreshold: MESSAGE_LIST_VISIBLE_PERCENT_THRESHOLD',);});++it('renders message bodies natively with in-place per-block selectable text', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const flowSource = readFileSync(resolve(process.cwd(), 'e2e/maestro/message_selection.yaml'), 'utf8');+ const bubbleStart = source.indexOf('function MessageBubble');+ const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);+ const bubbleSource = source.slice(bubbleStart, bubbleEnd);+ const markdownBodyStart = source.indexOf('function MarkdownBody');+ const markdownBodyEnd = source.indexOf('function renderInline', markdownBodyStart);+ const markdownBodySource = source.slice(markdownBodyStart, markdownBodyEnd);++ // 完成态才可选中;正文与 secondaryBody 都走原生 selectable。+ expect(source).toContain('const canSelectVisibleText = canUseCompletedActions && copyText.trim().length > 0;');+ expect(bubbleSource).toContain('selectable={canSelectVisibleText}');+ expect(bubbleSource).toContain('<MarkdownSelectableText selectable={canSelectVisibleText} style={styles.detailText}>');++ // iOS 部分选择:RN Text 底层是 UILabel 只能整块拷贝(facebook/react-native#13938),+ // 可选中块在 iOS 换用 react-native-uitextview(真 UITextView,系统选择手柄);+ // Android 维持 AppText selectable(本身有手柄)。嵌套 span 必须同为 UITextView 家族。+ expect(source).toContain("from 'react-native-uitextview'");+ expect(source).toContain('function MarkdownSelectableText({');+ expect(source).toContain("if (selectable && allowIosUITextView && Platform.OS === 'ios') {");+ expect(source).toContain('uiTextView');+ expect(source).toContain('function MarkdownSelectableSpan(');+ expect(source).toContain('const SpanText = ctx.SpanText ?? MessageBodyText;');+ expect(markdownBodySource).toContain('blockSelectable && allowIosUITextView && Platform.OS === \'ios\'');++ // 气泡是纯 View,不挂 Pressable/onLongPress(避免干扰横向 ScrollView 手势)。+ expect(bubbleSource).not.toContain('<Pressable');+ expect(bubbleSource).not.toContain('onLongPress');++ // 列表内正文只有原生渲染路径:无选择 WebView、无全屏选择查看器。+ expect(markdownBodySource).toContain('testID="message.markdownBody"');+ // Agent 回复二次测宽:stretch 量到像素宽后钉死,避免 UITextView 首帧偏矮被列表裁切。+ expect(markdownBodySource).toContain('nextSettledContentWidth');+ expect(markdownBodySource).toContain('collapsable={false}');+ expect(markdownBodySource).toContain('onLayout={handleSettledWidthLayout}');+ expect(markdownBodySource).toContain('pinContentWidth');+ expect(markdownBodySource).toContain('pinSettledWidth');+ expect(markdownBodySource).toContain("pinContentWidth ? { alignSelf: 'stretch' } : null");+ expect(markdownBodySource).toContain(+ 'style={pinSettledWidth ? { width: contentWidth, maxWidth: \'100%\' } : null}',+ );+ expect(markdownBodySource).toContain(+ "key={`${group.key}:${pinSettledWidth ? contentWidth : 'hug'}`}",+ );+ expect(markdownBodySource).not.toContain('SelectableMarkdownWebView');+ expect(source).not.toContain('SelectableMarkdownWebView');+ expect(source).not.toContain('MessageTextSelectionModal');+ expect(source).not.toContain('InlineSelectableMessageText');++ // 各块 Text 开原生选中,含内嵌图片 View 的块除外(Android 上 selectable+内嵌 View 有风险)。+ expect(markdownBodySource).toContain('const inlinesSelectable = useCallback((inlines: readonly MobileMarkdownInline[]) => (');+ expect(markdownBodySource).toContain("inline.type === 'image' && imageRendersPreview(inline)");+ expect(markdownBodySource).toContain('isMobileMarkdownImageDirectUrl(inline.url) || managedImagePreviewUrl(inline.url) !== null');+ expect(markdownBodySource).toContain('selectable={inlinesSelectable(block.inlines)}');++ // 跨段选择:连续纯文本块合并进同一个原生文本视图(text_run),原生选择手柄可横跨段落。+ // Android 上长 selectable Text 分块,避免单个超高原生文本视图干扰列表测高/滚动。+ expect(markdownBodySource).toContain('ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS');+ expect(markdownBodySource).toContain("...(Platform.OS === 'android' ? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS : {})");+ expect(markdownBodySource).toMatch(/const textRunGroupingOptions = useMemo[(][\s\S]*?imageRendersPreview,/);+ expect(markdownBodySource).not.toContain("selectable === true && Platform.OS === 'android'");+ expect(markdownBodySource).toContain('groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions)');+ expect(markdownBodySource).toContain('testID="message.markdownTextRun"');+ expect(markdownBodySource).toContain("lineHeight: layout.markdownBodyGap");+ expect(markdownBodySource).toContain('!block.textRunContinuation');+ expect(markdownBodySource).toContain('isTextRunContinuationGroup(group)');+ expect(markdownBodySource).toContain('height: layout.markdownBodyGap');+ expect(markdownBodySource).not.toContain('{ gap: layout.markdownBodyGap }');+ expect(source).toContain('mobileMarkdownImageAltChipText(inline.alt)');+ expect(markdownBodySource).toContain('selectable={inlinesSelectable(cell)}');+ expect(markdownBodySource).toContain('selectable={selectable === true}');++ // WebView 独有的用户气泡宽度估算 hack 不复活(原生 Text 自适应宽度)。+ expect(source).not.toContain('estimateSelectableUserBubbleWidth');++ // 列表滚动不被选择态钳制(原生选择手柄由系统处理,与列表滚动无关)。+ expect(source).not.toContain('scrollEnabled={!textSelectionActive}');++ // e2e 流程与新交互对齐:长按正文文字 → 系统选择菜单 → Copy。+ expect(flowSource).toContain('id: "message.markdownBody"');+ expect(flowSource).toContain('visible: "Copy"');+ expect(flowSource).toContain('- tapOn: "Copy"');+ expect(flowSource).not.toContain('message.textSelectionModal');+ expect(flowSource).not.toContain('message.selectableMarkdownBody');+ });});diff --git a/apps/mobile/src/__tests__/messageReadingRestore.test.ts b/apps/mobile/src/__tests__/messageReadingRestore.test.tsindex b09e51e9fa..9c676ae4e1 100644--- a/apps/mobile/src/__tests__/messageReadingRestore.test.ts+++ b/apps/mobile/src/__tests__/messageReadingRestore.test.ts@@ -50,7 +50,7 @@ function restore(focused: string | null = null, key = 'message') {listRef: { current: { scrollToIndex } },scrollToEndProgrammatically,};- expect(effect).not.toBe('');+ if (!effect) throw new Error('Missing production initial-position effect');const compiled = ts.transpileModule(`const run = ${effect};`, {compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },}).outputText;@@ -131,7 +131,7 @@ describe('top padding during bookmark restoration', () => {scrollMetricsRef: { current: { offsetY: sequence ? 600 : 0 } },scrollToOffsetProgrammatically: vi.fn(),};- expect(paddingEffect).not.toBe('');+ if (!paddingEffect) throw new Error('Missing production top-padding effect');const compiled = ts.transpileModule(`const run = ${paddingEffect};`, {compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },}).outputText;diff --git a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.tsdeleted file mode 100644index 9b9ae66098..0000000000--- a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--// 消息文本选择契约(2026-07 起):-// - 列表内所有消息正文一律原生 markdown 渲染,不再"每条完成消息挂一个选择 WebView"-// (旧方案冷开 ~80 个 WebView 同时挂载,是内存 / 首屏 / 滚动的最大热点)。-// - 文本选择 = 完成态消息各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,-// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界)。-// - 气泡必须是纯 View:挂 Pressable 会参与触摸协商,干扰正文里表格/代码块横向 ScrollView 的拖动。-describe('mobile message text selection', () => {- it('renders message bodies natively with in-place per-block selectable text', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const flowSource = readFileSync(resolve(process.cwd(), 'e2e/maestro/message_selection.yaml'), 'utf8');- const bubbleStart = source.indexOf('function MessageBubble');- const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);- const bubbleSource = source.slice(bubbleStart, bubbleEnd);- const markdownBodyStart = source.indexOf('function MarkdownBody');- const markdownBodyEnd = source.indexOf('function renderInline', markdownBodyStart);- const markdownBodySource = source.slice(markdownBodyStart, markdownBodyEnd);-- // 完成态才可选中;正文与 secondaryBody 都走原生 selectable。- expect(source).toContain('const canSelectVisibleText = canUseCompletedActions && copyText.trim().length > 0;');- expect(bubbleSource).toContain('selectable={canSelectVisibleText}');- expect(bubbleSource).toContain('<MarkdownSelectableText selectable={canSelectVisibleText} style={styles.detailText}>');-- // iOS 部分选择:RN Text 底层是 UILabel 只能整块拷贝(facebook/react-native#13938),- // 可选中块在 iOS 换用 react-native-uitextview(真 UITextView,系统选择手柄);- // Android 维持 AppText selectable(本身有手柄)。嵌套 span 必须同为 UITextView 家族。- expect(source).toContain("from 'react-native-uitextview'");- expect(source).toContain('function MarkdownSelectableText({');- expect(source).toContain("if (selectable && allowIosUITextView && Platform.OS === 'ios') {");- expect(source).toContain('uiTextView');- expect(source).toContain('function MarkdownSelectableSpan(');- expect(source).toContain('const SpanText = ctx.SpanText ?? MessageBodyText;');- expect(markdownBodySource).toContain('blockSelectable && allowIosUITextView && Platform.OS === \'ios\'');-- // 气泡是纯 View,不挂 Pressable/onLongPress(避免干扰横向 ScrollView 手势)。- expect(bubbleSource).not.toContain('<Pressable');- expect(bubbleSource).not.toContain('onLongPress');-- // 列表内正文只有原生渲染路径:无选择 WebView、无全屏选择查看器。- expect(markdownBodySource).toContain('testID="message.markdownBody"');- // Agent 回复二次测宽:stretch 量到像素宽后钉死,避免 UITextView 首帧偏矮被列表裁切。- expect(markdownBodySource).toContain('nextSettledContentWidth');- expect(markdownBodySource).toContain('collapsable={false}');- expect(markdownBodySource).toContain('onLayout={handleSettledWidthLayout}');- expect(markdownBodySource).toContain('pinContentWidth');- expect(markdownBodySource).toContain('pinSettledWidth');- expect(markdownBodySource).toContain("pinContentWidth ? { alignSelf: 'stretch' } : null");- expect(markdownBodySource).toContain(- 'style={pinSettledWidth ? { width: contentWidth, maxWidth: \'100%\' } : null}',- );- expect(markdownBodySource).toContain(- "key={`${group.key}:${pinSettledWidth ? contentWidth : 'hug'}`}",- );- expect(markdownBodySource).not.toContain('SelectableMarkdownWebView');- expect(source).not.toContain('SelectableMarkdownWebView');- expect(source).not.toContain('MessageTextSelectionModal');- expect(source).not.toContain('InlineSelectableMessageText');-- // 各块 Text 开原生选中,含内嵌图片 View 的块除外(Android 上 selectable+内嵌 View 有风险)。- expect(markdownBodySource).toContain('const inlinesSelectable = useCallback((inlines: readonly MobileMarkdownInline[]) => (');- expect(markdownBodySource).toContain("inline.type === 'image' && imageRendersPreview(inline)");- expect(markdownBodySource).toContain('isMobileMarkdownImageDirectUrl(inline.url) || managedImagePreviewUrl(inline.url) !== null');- expect(markdownBodySource).toContain('selectable={inlinesSelectable(block.inlines)}');-- // 跨段选择:连续纯文本块合并进同一个原生文本视图(text_run),原生选择手柄可横跨段落。- // Android 上长 selectable Text 分块,避免单个超高原生文本视图干扰列表测高/滚动。- expect(markdownBodySource).toContain('ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS');- expect(markdownBodySource).toContain("...(Platform.OS === 'android' ? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS : {})");- expect(markdownBodySource).toMatch(/const textRunGroupingOptions = useMemo[(][\s\S]*?imageRendersPreview,/);- expect(markdownBodySource).not.toContain("selectable === true && Platform.OS === 'android'");- expect(markdownBodySource).toContain('groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions)');- expect(markdownBodySource).toContain('testID="message.markdownTextRun"');- expect(markdownBodySource).toContain("lineHeight: layout.markdownBodyGap");- expect(markdownBodySource).toContain('!block.textRunContinuation');- expect(markdownBodySource).toContain('isTextRunContinuationGroup(group)');- expect(markdownBodySource).toContain('height: layout.markdownBodyGap');- expect(markdownBodySource).not.toContain('{ gap: layout.markdownBodyGap }');- expect(source).toContain('mobileMarkdownImageAltChipText(inline.alt)');- expect(markdownBodySource).toContain('selectable={inlinesSelectable(cell)}');- expect(markdownBodySource).toContain('selectable={selectable === true}');-- // WebView 独有的用户气泡宽度估算 hack 不复活(原生 Text 自适应宽度)。- expect(source).not.toContain('estimateSelectableUserBubbleWidth');-- // 列表滚动不被选择态钳制(原生选择手柄由系统处理,与列表滚动无关)。- expect(source).not.toContain('scrollEnabled={!textSelectionActive}');-- // e2e 流程与新交互对齐:长按正文文字 → 系统选择菜单 → Copy。- expect(flowSource).toContain('id: "message.markdownBody"');- expect(flowSource).toContain('visible: "Copy"');- expect(flowSource).toContain('- tapOn: "Copy"');- expect(flowSource).not.toContain('message.textSelectionModal');- expect(flowSource).not.toContain('message.selectableMarkdownBody');- });-});diff --git a/apps/mobile/src/__tests__/messageSelectionHighlight.test.ts b/apps/mobile/src/__tests__/messageSelectionHighlight.test.tsindex da6e1c1ea4..46c11d0166 100644--- a/apps/mobile/src/__tests__/messageSelectionHighlight.test.ts+++ b/apps/mobile/src/__tests__/messageSelectionHighlight.test.ts@@ -1,3 +1,4 @@+// guard: DESIGN.md contrast/readability and #1427: system-native selection highlighting must not be overwritten by an opaque per-view color; static native-renderer contract.import { readFile } from 'node:fs/promises';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsxindex 508f903185..ec8f5703cc 100644--- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx+++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx@@ -18,7 +18,7 @@ const viewportHarness = vi.hoisted(() => ({vi.mock("react-native", async () => {const React = await import("react");// onLongPress 映射到 contextmenu,便于测试长按显示来源 ID。- const view = ({ children, testID, accessibilityLabel, accessibilityHint, onLongPress }: any) =>+ const view = ({ children, testID, accessibilityLabel, accessibilityHint, onLongPress, onPress, disabled }: any) =>React.createElement("div",{@@ -26,6 +26,8 @@ vi.mock("react-native", async () => {"aria-label": accessibilityLabel,...(accessibilityHint ? { "data-hint": accessibilityHint } : {}),...(onLongPress ? { onContextMenu: () => onLongPress() } : {}),+ ...(onPress ? { onClick: disabled ? undefined : onPress } : {}),+ ...(disabled ? { 'aria-disabled': true } : {}),},children,);@@ -145,7 +147,7 @@ vi.mock("react-native-svg", () => ({default: () => null,Circle: () => null,}));-vi.mock("react-native-uitextview", () => ({ UITextView: () => null }));+vi.mock("react-native-uitextview", async () => ({ UITextView: (await import('react-native')).Text }));vi.mock("expo-image", () => ({ Image: () => null }));vi.mock("expo-router", () => ({useRouter: () => ({ push: vi.fn() }),@@ -196,7 +198,7 @@ vi.mock("@/session/expandedBlockMemory", () => ({useFoldableExpandedState: () => [false, vi.fn()],}));vi.mock("@/platform/chrome", () => ({- NativePullDownMenu: () => null,+ NativePullDownMenu: ({ children }: any) => children,showActionMenu: vi.fn(),usesNativePullDownMenu: () => false,usesSystemActionMenu: () => false,@@ -266,16 +268,21 @@ function render(messages: RemoteMessage[],props: Record<string, unknown> = {},): string {- const items = buildMobileMessageRenderItems(messages, {}).filter(+ const mounted = mount(messages, props);+ const html = mounted.host.innerHTML;+ mounted.unmount();+ return html;+}++function mount(messages: RemoteMessage[], props: Record<string, unknown> = {}) {+ const items = buildMobileMessageRenderItems(messages, { isSessionStreaming: props.isSessionStreaming === true }).filter((item) => item.type === "message",);Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });const host = document.createElement("div");const root = createRoot(host);act(() => root.render(<MessageRenderer items={items} {...props} />));- const html = host.innerHTML;- act(() => root.unmount());- return html;+ return { host, unmount: () => act(() => root.unmount()) };}beforeAll(async () => {@@ -367,6 +374,40 @@ describe("message delete entry", () => {});});+describe('completed message actions', () => {+ // Production render/model gate: source scans could pass with an action bar+ // attached to system cards, or More exposed on an intermediate assistant row.+ it('omits user controls on user-kind system cards and incomplete assistant rows', () => {+ const props = { onForkMessage: vi.fn(), onPreviewRewind: vi.fn(),+ onDeleteMessage: vi.fn(), onCopyMessageLink: vi.fn(), onAddMessageToComposer: vi.fn() };+ const card = render([{ ...msg('card', '', null), systemCardType: 'pwd' }], props);+ expect(card).not.toContain('message.userBubble');+ expect(card).not.toContain('message.actionBar');+ const partial = mount([msg('question', 'Question', null), { ...msg('partial', 'Working', { isStreaming: true }), role: 'assistant' }],+ { ...props, isSessionStreaming: true });+ try {+ expect(partial.host.querySelectorAll('section')[1].querySelector('[data-testid="message.moreButton"]')).toBeNull();+ } finally { partial.unmount(); }+ const final = render([{ ...msg('final', 'Done', { turnCompleted: true }), role: 'assistant' }], props);+ expect(final).toContain('message.moreButton');+ });++ it('places controls outside the bubble and forks the selected row exactly once', () => {+ const onForkMessage = vi.fn();+ const h = mount([msg('first', 'Question', null), msg('second', 'Follow-up', null)], { onForkMessage });+ try {+ const bubble = h.host.querySelector('[data-testid="message.userBubble"]')!;+ expect(bubble.querySelector('[data-testid="message.actionBar"]')).toBeNull();+ const fork = h.host.querySelector('[data-testid="message.forkButton"]')!;+ expect(fork).not.toBeNull();+ act(() => fork.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(onForkMessage).toHaveBeenCalledExactlyOnceWith('second', {+ text: 'Follow-up', quotes: [], document: { version: 1, nodes: [{ type: 'text', text: 'Follow-up' }] },+ });+ } finally { h.unmount(); }+ });+});+describe("sender source labels", () => {it("renders plugin, shared-task author (above the bubble) and redacted automation labels", () => {const html = render([diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.tsindex 1759b2d761..6a0092fe04 100644--- a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts@@ -1,6 +1,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { beforeEach, describe, expect, it } from 'vitest';+import * as React from 'react';+import ts from 'typescript';import {getMobileMessageWebViewMetrics,registerMobileMessageWebView,@@ -33,48 +35,20 @@ describe('mobile message WebView lifecycle accounting', () => {});});-describe('message WebView visibility wiring', () => {- it('gates heavy message blocks without changing the list virtualization contract', () => {- const renderer = readFileSync(- resolve(process.cwd(), 'src/session/MessageRenderer.tsx'),- 'utf8',- );- const mermaid = readFileSync(resolve(process.cwd(), 'src/session/mermaidWebView.tsx'), 'utf8');- const math = readFileSync(resolve(process.cwd(), 'src/session/mathWebView.tsx'), 'utf8');- const media = readFileSync(resolve(process.cwd(), 'src/session/mediaPlayerWebView.tsx'), 'utf8');- const composer = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');-- expect(renderer).not.toContain('MessageListVisibleKeysContext');- expect(renderer).toContain('useMessageListItemVisible(item.key)');- expect(renderer).toContain('onViewableItemsChanged={handleViewableItemsChanged}');- expect(renderer).toContain('const heavyContentVisible = focused || isViewable;');- expect(renderer).toContain('function ViewabilityGatedMermaidDiagram(');- expect(renderer).toContain('function ViewabilityGatedMathFormula(');- expect(renderer).toContain('active={heavyContentVisible}');- const markdownBodyStart = renderer.indexOf('function MarkdownBody(');- const markdownBodyEnd = renderer.indexOf('\nfunction ', markdownBodyStart + 1);- const markdownBody = renderer.slice(markdownBodyStart, markdownBodyEnd);- expect(markdownBody).not.toContain('useContext(MessageHeavyContentVisibilityContext)');- expect(renderer).toContain('getWebViewMetrics: getMobileMessageWebViewMetrics');- expect(renderer).toContain('getMarkdownMetrics: getMobileMarkdownRenderMetrics');- expect(renderer).toContain('devRecycleItems = false,');- expect(renderer).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : false;');- expect(renderer).toContain('recycleItems={recycleItems}');- expect(renderer).toContain('getItemType={mobileMessageListItemType}');- expect(mermaid).toContain('active?: boolean;');- expect(mermaid).toMatch(/mountWebView\s*\?\s*<WebView/);- expect(mermaid).toContain('useDeferredRichContent(active && !preview');- expect(math).toContain('active?: boolean;');- expect(math).toMatch(/mountWebView\s*\?\s*<WebView/);- expect(math).toContain('useDeferredRichContent(active &&');- expect(math).toContain('renderGenerationRef.current !== renderGeneration');- expect(mermaid).toContain('pendingExportsRef.current.clear();');- expect(mermaid).toContain('}, [active, source]);');- expect(media).toContain('stopPlaybackAndLoading');- expect(media).toContain('webViewRef.current?.stopLoading();');- expect(media).toContain('lifecycleRef.current.consumeReloadOnActive()');- expect(media).toContain('key={reloadGeneration}');- expect(media).toContain('if (!mountedRef.current) return;');- expect(composer).toContain('if (disposedRef.current) return;');- });+// Actual native rich-view lifecycle is covered by richContentViews.test.tsx.+// Keep the consumer gate behavioral: a hidden item must pass inactive to the host.+it.each([false, true])('passes visible=%s to both rich-content hosts', (active) => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const tree = ts.createSourceFile('renderer.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const functions: ts.Node[] = [];+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ['ViewabilityGatedMermaidDiagram', 'ViewabilityGatedMathFormula'].includes(node.name.getText(tree))) functions.push(node);+ ts.forEachChild(node, visit);+ }+ visit(tree);+ const code = ts.transpileModule(functions.map((node) => 'const ' + node.getText(tree) + ';').join('\n'), { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+ const bindings = { React, memo: (component: unknown) => component, useContext: () => active, MessageHeavyContentVisibilityContext: {}, MermaidDiagramWebView: 'MermaidHost', MathFormulaWebView: 'MathHost' };+ const hosts = new Function(...Object.keys(bindings), code + '\nreturn [ViewabilityGatedMermaidDiagram, ViewabilityGatedMathFormula];')(...Object.values(bindings));+ if (hosts.length !== 2) throw new Error('Missing production rich-content visibility gates');+ for (const render of hosts) expect(render({ source: 'content', testID: 'rich' }).props).toMatchObject({ active, source: 'content', testID: 'rich' });});diff --git a/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.tsindex f0d3487f67..064285f5ae 100644--- a/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts+++ b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts@@ -1,7 +1,9 @@// @ts-nocheck —— 被测对象是 .mjs 开发工具模块,vitest 跑其纯函数与注入式流程。import { readFileSync } from 'node:fs';import { resolve, win32 } from 'node:path';+import { runInNewContext } from 'node:vm';import { describe, expect, it, vi } from 'vitest';+import { resolvePnpmInvocation, usablePnpmExecPath } from '../../../../scripts/shared/pnpm-invocation.mjs';import {DEFAULT_ANDROID_AVD,ensureWindowsAndroidEmulator,@@ -12,11 +14,51 @@ import {} from '../../scripts/lib/android-simulator.mjs';describe('Windows Android 模拟器参数', () => {- it('sim:start 使用跨平台 pnpm 调用器,不再直接 spawn pnpm', () => {+ // Execute the actual launch tail: losing the resolver or its cmd environment+ // makes Windows fail before Expo starts (engineering-conventions.md §3.2).+ it.each([+ ['available pnpm script', 'C:\\tools\\pnpm.cjs', true],+ ['removed pnpm script', 'C:\\tools\\pnpm.cjs', false],+ ['unrelated npm executable', 'C:\\tools\\npm-cli.js', true],+ ])('sim:start preserves the Windows invocation for %s', async (_name, npmExecPath, present) => {const source = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');- expect(source).toContain('resolvePnpmInvocation(args');- expect(source).toContain('usablePnpmExecPath(process.env.npm_execpath, existsSync)');- expect(source).not.toContain("spawn('pnpm'");+ const start = source.indexOf("const args = ['exec', 'expo', 'start'");+ if (start < 0) throw new Error('Missing sim:start launch flow');+ const spawn = vi.fn(() => ({ once: vi.fn(), on: vi.fn() }));+ const ensureAndroidTarget = vi.fn();+ const node = 'C:\\Node\\node.exe';+ const cmd = 'C:\\Windows\\cmd.exe';+ await runInNewContext(`(async () => { ${source.slice(start)} })()`, {+ DEFAULT_PORT: 8081, portArgs: { port: 8082, passthrough: ['--clear'] },+ portInUse: async () => false, ensureAndroidTarget, spawn,+ console: { log: vi.fn(), error: vi.fn() },+ process: { env: { npm_execpath: npmExecPath, KEEP: 'inherited' } },+ resolvePnpmInvocation: (args, options) => resolvePnpmInvocation(args, { ...options, platform: 'win32', execPath: node, comSpec: cmd }),+ usablePnpmExecPath, existsSync: (target) => present && target === npmExecPath,+ mobileDir: 'C:\\repo\\apps\\mobile', worktreeRoot: 'C:\\repo',+ buildEnv: { CINDY_USE_LOCAL_REGION_CONFIG: '1' }, region: 'global',+ branch: 'test', commit: '123', sourceIdentity: 'test@123',+ });+ expect(ensureAndroidTarget).toHaveBeenCalledOnce();+ expect(spawn).toHaveBeenCalledOnce();+ const [command, args, options] = spawn.mock.calls[0];+ const expoArgs = ['exec', 'expo', 'start', '--dev-client', '--clear', '--port', '8082'];+ if (present && npmExecPath.endsWith('pnpm.cjs')) {+ expect(command).toBe(node);+ expect(args).toEqual([npmExecPath, ...expoArgs]);+ expect(options.windowsVerbatimArguments).toBeUndefined();+ } else {+ expect(command).toBe(cmd);+ expect(args.slice(0, 4)).toEqual(['/d', '/s', '/v:off', '/c']);+ expect(args[4]).toContain('%CINDY_PNPM_CMD_ARG_0%');+ expect(Object.entries(options.env)+ .filter(([key]) => key.startsWith('CINDY_PNPM_CMD_ARG_'))+ .sort(([left], [right]) => Number(left.split('_').at(-1)) - Number(right.split('_').at(-1)))+ .map(([, value]) => value)).toEqual(['pnpm', ...expoArgs]);+ expect(options.windowsVerbatimArguments).toBe(true);+ }+ expect(options).toMatchObject({ cwd: 'C:\\repo\\apps\\mobile', shell: false, stdio: 'inherit',+ env: { KEEP: 'inherited', CINDY_USE_LOCAL_REGION_CONFIG: '1', EXPO_PUBLIC_XDT_GIT_SOURCE: 'test@123' } });});it('Windows 默认启动 cindy-api36,且不把本地参数透传给 Expo', () => {diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex 236a259aff..e4cc3b67db 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -1,3 +1,4 @@+// guard: credentials-and-local-storage.md and protocol-compatibility.md: PKCE, rotating credentials, account replacement and native login bridges must preserve their cross-file trust boundaries.import { readFileSync as readFileSyncRaw } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';diff --git a/apps/mobile/src/__tests__/mobileHomeSharedTasks.test.ts b/apps/mobile/src/__tests__/mobileHomeSharedTasks.test.tsindex 35f0810b0a..82ee430a62 100644--- a/apps/mobile/src/__tests__/mobileHomeSharedTasks.test.ts+++ b/apps/mobile/src/__tests__/mobileHomeSharedTasks.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from 'vitest';+import ts from 'typescript';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { sharedTaskHostPeer } from '@cindy/device-link';@@ -134,34 +135,20 @@ describe('shared Home group', () => {});});-describe('shared role row wiring', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');-- it('adds roles only to the existing shared group and still hides an empty group', () => {- expect(source).toContain('ListHeaderComponent={sharedRows.length > 0 ?');- expect(source.match(/sharedRole={row.role}/g)).toHaveLength(1);- expect(source).toContain('testID={`home.sharedRoleSlot.owned.${row.task.sessionId}`}');- });-- it('uses a fixed title-side role slot and only renders a crown for owners', () => {- expect(source).toContain('const showPreviewLine = !textMode && (!!group || !!preview?.trim() || showSchedule || showPinned);');- const row = source.slice(source.indexOf('function HomeSessionRowInner('), source.indexOf('function AutomationGroupChildren('));- const roleSlot = row.indexOf('testID={`home.sharedRoleSlot.owned.${item.session.id}`}');- expect(roleSlot).toBeGreaterThan(row.indexOf('<SessionStatusMark'));- expect(roleSlot).toBeLessThan(row.indexOf('styles.sessionListContent'));- expect(row).toContain("{sharedRole === 'owned' ? (");- expect(row).not.toContain('{sharedRole ? (');- expect(row).not.toContain('accessibilityElementsHidden');- expect(row).not.toContain('importantForAccessibility');- expect(row).toContain("const accessibilityTitle = sharedRole === 'owned' ? item.title + ', ' + t('sharedTask.roleHost') : item.title;");- expect(row).toContain("t('devices.list.a11y.openAutomationLatest', { title: accessibilityTitle })");- expect(row).toContain("t('devices.list.a11y.automationTask', { title: accessibilityTitle })");- expect(row).toContain('accessibilityLabel={accessibilityLabel}');- expect(row).toContain('accessible={false}');- expect(row).not.toContain("accessibilityLabel={t('sharedTask.roleHost')}");- expect(row).not.toContain('sharedRoleBadge');- expect(row).toContain('color={colors.warningFg}');- expect(source).not.toContain('roleOwnedBadge');- expect(source).not.toContain('roleJoinedBadge');+// Shared role identity and filtering run above through the production presentation.+// Check the production row's accessibility projection rather than crown/layout strings.+describe('shared role accessibility', () => {+ it.each(['owned', 'joined', undefined] as const)('announces ownership only for role %s', (sharedRole) => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');+ const tree = ts.createSourceFile('HomeSurface.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'accessibilityTitle') initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!initializer) throw new Error('Missing production row accessibility title');+ const project = new Function('sharedRole', 'item', 't', 'return (' + initializer.getText(tree) + ');');+ expect(project(sharedRole, { title: 'Task' }, (key: string) => key)).toBe(sharedRole === 'owned' ? 'Task, sharedTask.roleHost' : 'Task');});});diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex ce2b205cef..d3e69d87db 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from "node:fs";-import { resolve } from "node:path";import { describe, expect, it, vi } from "vitest";import {CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,@@ -638,24 +636,9 @@ describe("mobile maker transport", () => {});it("does not advertise or emit the unimplemented model-window confirmation protocol", async () => {- const contextSource = readFileSync(- resolve(process.cwd(), "src/device-link/DeviceLinkContext.tsx"),- "utf8",- );- const transportSource = readFileSync(- resolve(process.cwd(), "src/device-link/mobileMakerTransport.ts"),- "utf8",- );const { calls, maker } = harness();await maker.setModel("s1", "small-model", "anthropic");-- expect(contextSource).not.toContain(- "CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1",- );- expect(contextSource).not.toContain("model-window-confirmation-v1");- expect(transportSource).not.toContain("confirmedOverflow");- expect(transportSource).not.toContain("confirmedContextWindow");expect(calls).toEqual([{deviceId: "dev-1",diff --git a/apps/mobile/src/__tests__/mobileModelPickerLayout.test.ts b/apps/mobile/src/__tests__/mobileModelPickerLayout.test.tsdeleted file mode 100644index 91c754fe8b..0000000000--- a/apps/mobile/src/__tests__/mobileModelPickerLayout.test.ts+++ /dev/null@@ -1,50 +0,0 @@-/**- * Mobile model-picker row layout contract.- *- * React Native components cannot load in the Node Vitest environment, so this test locks the- * source structure that keeps secondary metadata from consuming the model-name line.- */-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--const source = readFileSync(- resolve(process.cwd(), 'src/session/MobileModelPickerList.tsx'),- 'utf8',-).replace(/\s+/g, ' ');--describe('MobileModelPickerList compact rows', () => {- it('gives provider-aware model names a dedicated primary line above the meta line', () => {- const modelName = source.indexOf('{row.model.displayName}');- const metadata = source.indexOf('{metaLine ? (', modelName);-- expect(modelName).toBeGreaterThan(-1);- expect(metadata).toBeGreaterThan(modelName);- expect(source.slice(modelName, metadata)).toContain('</Text>');- });-- it('keeps subscription, effort and Fast in one secondary line like iOS', () => {- expect(source).toContain("isSubscription ? t('models.picker.subscriptionBadge') : null,");- expect(source).toContain('fullEffortLabel,');- expect(source).toContain("fastOn ? t('models.options.fastMode') : null,");- expect(source).toContain(".join(' · ');");- expect(source.match(/accessibilityLabel=\{rowAccessibilityLabel\}/g)).toHaveLength(2);- // 选中只用勾号表达,不再铺整行底色。- expect(source).not.toContain('optionRowSelected');- });-- it('groups provider rows by source with a source · account title', () => {- expect(source).toContain('groups.set(row.provider.id, rows);');- expect(source).toContain("identity && !provider.name.includes(identity) ? identity : null,");- expect(source).toContain('style={styles.groupLabel}>{groupTitle}</Text>');- });-- it('uses the same primary and secondary hierarchy for flat fallback rows', () => {- const modelName = source.indexOf('{option.label}');- const metadata = source.indexOf('{metaLine ? (', modelName);-- expect(modelName).toBeGreaterThan(-1);- expect(metadata).toBeGreaterThan(modelName);- expect(source.slice(modelName, metadata)).toContain('</Text>');- });-});diff --git a/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts b/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.tsnew file mode 100644index 0000000000..e9e4fa7a22--- /dev/null+++ b/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts@@ -0,0 +1,293 @@+import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it } from 'vitest';++// guard: export spans Swift rendering, a hidden WebView, and the system share+// extension's deferred file read. These contracts cannot run in the JS unit host.+it('bounds native export and preserves the hidden document and system share boundaries', () => {+ const native = readFileSync(resolve(process.cwd(), 'modules/xdt-screenshot-monitor/ios/XdtScreenshotMonitorModule.swift'), 'utf8');+ expect(native).toContain('captureWidth * captureHeight <= conversationShareMaxSourcePixels');+ expect(native).toContain('waitForWebContentPaint(webView)');+ expect(native).toContain('merged.hasVisibleVariation');+ expect(native).toContain('no active window scene');+ expect(native).toContain('hostingWindow?.isHidden = true');+ const web = readFileSync(resolve(process.cwd(), 'src/session/ConversationShareWebView.tsx'), 'utf8');+ expect(web).toContain('onShouldStartLoadWithRequest={interceptNavigation}');+ expect(web).toContain('interceptHtmlNavigation(request, documentSettledRef.current)');+ expect(web).toContain('allowFileAccess={false}');+ expect(web).toContain('mediaCapturePermissionGrantType="deny"');+ const route = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');+ const share = route.indexOf("await sharing.shareAsync(localUri, { mimeType: 'image/png' });");+ const completed = route.indexOf('shareCompleted = true;', share);+ const inactive = route.indexOf('if (!isShareOperationActive()) return;', share);+ expect(share).toBeGreaterThanOrEqual(0);+ expect(completed).toBeGreaterThan(share);+ expect(inactive).toBeGreaterThan(completed);+ expect(route).toContain('if (!shareCompleted && localUri)');+});++// guard: native WebView commands and late callbacks cross the React/native host+// boundary; the runtime models and richContentViews exercise their behavior.+it('cancels native player loading and rejects callbacks after editor disposal', () => {+ const media = readFileSync(resolve(process.cwd(), 'src/session/mediaPlayerWebView.tsx'), 'utf8');+ const composer = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');+ expect(media).toContain('webViewRef.current?.stopLoading();');+ expect(media).toContain('lifecycleRef.current.consumeReloadOnActive()');+ expect(media).toContain('if (!mountedRef.current) return;');+ expect(composer).toContain('if (disposedRef.current) return;');+});++// guard: mobile-development.md native/runtime boundary and engineering-conventions.md section 3.2.+// Native distribution authority, recording cleanup, and delegate/JS call sites must stay connected.+// JS unit tests exercise their bridges but cannot execute Swift, Android delegates, or native clipping.+// Keep existing cross-runtime assertions here; do not substitute these for the unit behavior suites.+describe('mobile native boundary contracts', () => {+ it('keeps StoreKit 2 authoritative and receipt lookup as a fallback', () => {+ const swift = readFileSync(+ resolve(+ process.cwd(),+ 'modules/xdt-ios-app-distribution/ios/XdtIosAppDistributionModule.swift',+ ),+ 'utf8',+ );+ const moduleConfig = readFileSync(+ resolve(process.cwd(), 'modules/xdt-ios-app-distribution/expo-module.config.json'),+ 'utf8',+ );+ const endpointGate = readFileSync(+ resolve(process.cwd(), 'src/config/useStartupEndpointGate.ts'),+ 'utf8',+ );+ const startupBundleCheck = readFileSync(+ resolve(process.cwd(), 'src/update/useBundleUpdatePrompt.ts'),+ 'utf8',+ );+ const resumeUpdateCheck = readFileSync(+ resolve(process.cwd(), 'src/update/useResumeUpdateCheck.ts'),+ 'utf8',+ );+ const settings = readFileSync(+ resolve(process.cwd(), 'app/settings.tsx'),+ 'utf8',+ );++ expect(swift).toContain('try await AppTransaction.shared');+ expect(swift).toContain('case .verified(let transaction)');+ expect(swift).toContain('case .sandbox:');+ expect(swift).toContain('receiptName == "sandboxReceipt"');+ expect(moduleConfig).toContain('"platforms": ["apple"]');+ expect(moduleConfig).not.toContain('"android"');+ // The async StoreKit lookup must complete inside the endpoint gate, before+ // REVIEW_MODE is consumed by any update hook or settings screen.+ expect(endpointGate).toContain('resolveIsTestFlight: isTestFlightBuild');+ // Startup, settings, and resume must all consume the resolved TestFlight+ // state before deciding whether the full-package channel is available.+ for (const source of [startupBundleCheck, settings, resumeUpdateCheck]) {+ expect(source).toContain('isTestFlightBuild: IS_TESTFLIGHT_BUILD');+ }+ });++ it('keeps the iOS native realtime recorder wired for interruption cleanup', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift'),+ 'utf8',+ );++ expect(source).toContain('AVAudioSession.interruptionNotification');+ expect(source).toContain('AVAudioSession.routeChangeNotification');+ expect(source).toContain('removeAudioSessionObservers()');+ expect(source).toContain('handleAudioSessionInterruption');+ expect(source).toContain('handleAudioRouteChange');+ expect(source).toContain('OnAppEntersBackground');+ expect(source).toContain('stopCapture(deactivateImmediately: true)');+ expect(source).toContain('stopCapture()');+ expect(source).toContain('unsignedIntegerValue(notification.userInfo?[AVAudioSessionInterruptionTypeKey])');+ expect(source).toContain('unsignedIntegerValue(notification.userInfo?[AVAudioSessionRouteChangeReasonKey])');+ });++ it('cancels voice runs in both composers when the app enters the background', () => {+ const newSessionSource = readFileSync(+ resolve(process.cwd(), 'app/sessions/new.tsx'),+ 'utf8',+ );+ const existingSessionSource = readFileSync(+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),+ 'utf8',+ );++ for (const source of [newSessionSource, existingSessionSource]) {+ expect(source).toContain("AppState.addEventListener('change'");+ expect(source).toContain("nextState !== 'background'");+ expect(source).toContain('voiceControllerSessionRef.current = null');+ expect(source).toContain('discardPendingPrewarm()');+ expect(source).not.toContain("setAudioModeAsync");+ }+ expect(newSessionSource).toContain('cancelVoiceForDeviceSwitch();');+ expect(existingSessionSource).toContain('cancelVoiceForAppBackground();');+ });++ it('wires first-party Apple, public Google, and the minimal official WeChat bridge', () => {+ const appJson = JSON.parse(+ readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),+ );+ const packageJson = JSON.parse(+ readFileSync(resolve(process.cwd(), 'package.json'), 'utf8'),+ );+ const configSource = readFileSync(+ resolve(process.cwd(), 'app.config.js'),+ 'utf8',+ );+ const pluginSource = readFileSync(+ resolve(process.cwd(), 'modules/xdt-wechat-login/plugin/index.js'),+ 'utf8',+ );+ const iosPodspec = readFileSync(+ resolve(+ process.cwd(),+ 'modules/xdt-wechat-login/ios/XdtWechatLogin.podspec',+ ),+ 'utf8',+ );+ const androidGradle = readFileSync(+ resolve(process.cwd(), 'modules/xdt-wechat-login/android/build.gradle'),+ 'utf8',+ );+ const moduleConfig = readFileSync(+ resolve(+ process.cwd(),+ 'modules/xdt-wechat-login/expo-module.config.json',+ ),+ 'utf8',+ );+ const iosCoordinator = readFileSync(+ resolve(+ process.cwd(),+ 'modules/xdt-wechat-login/ios/XdtWechatAuthCoordinator.swift',+ ),+ 'utf8',+ );+ const iosWechatPodfilePlugin = readFileSync(+ resolve(process.cwd(), 'plugins/with-wechat-opensdk-modulemap.js'),+ 'utf8',+ );+ const iosSubscriber = readFileSync(+ resolve(+ process.cwd(),+ 'modules/xdt-wechat-login/ios/XdtWechatLoginAppDelegateSubscriber.swift',+ ),+ 'utf8',+ );++ expect(appJson.expo.ios.usesAppleSignIn).toBe(true);+ expect(appJson.expo.plugins).toContain('expo-apple-authentication');+ expect(packageJson.dependencies['expo-apple-authentication']).toBeTruthy();+ expect(+ packageJson.dependencies['@react-native-google-signin/google-signin'],+ ).toBe('16.1.2');+ expect(packageJson.dependencies['xdt-wechat-login']).toBe(+ 'file:./modules/xdt-wechat-login',+ );+ expect(+ existsSync(+ resolve(+ process.cwd(),+ 'modules/xdt-feishu-login/expo-module.config.json',+ ),+ ),+ ).toBe(false);+ expect(configSource).toContain(+ "'@react-native-google-signin/google-signin'",+ );+ expect(configSource).toContain("'xdt-wechat-login/plugin'");+ expect(pluginSource).toContain("'weixinULAPI'");+ expect(pluginSource).toContain("'.wxapi.WXEntryActivity'");+ expect(pluginSource).toContain('withWechatEntryActivity(config, appId)');+ expect(pluginSource).toContain('createWXAPI(this, ${kotlinAppId}, false)');+ expect(iosPodspec).toContain("s.dependency 'WechatOpenSDK', '2.0.5'");+ expect(androidGradle).toContain('wechat-sdk-android:6.8.38');+ expect(moduleConfig).toContain('XdtWechatLoginAppDelegateSubscriber');+ expect(iosCoordinator).toContain(+ 'WXApi.handleOpenUniversalLink(userActivity, delegate: self)',+ );+ expect(iosCoordinator).toContain('#if targetEnvironment(simulator)');+ expect(iosCoordinator).toContain('ERR_WECHAT_UNAVAILABLE_ON_SIMULATOR');+ expect(iosWechatPodfilePlugin).toContain(+ 'xdt-wechat-login: arm64 simulator stub linkage',+ );+ expect(iosWechatPodfilePlugin).toContain(+ "other_linker_flags[:libraries].delete?('WechatOpenSDK')",+ );+ expect(iosWechatPodfilePlugin).toContain(+ "OTHER_LDFLAGS[sdk=iphoneos*]",+ );+ expect(iosSubscriber).toContain('continue userActivity: NSUserActivity');+ });++ // DESIGN §5: the same native ancestor must clip input, palette, and held cards.+ it('keeps all bottom controls under the native reservation clipping ancestor', () => {+ const source = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const elements = new Map<string, ts.JsxElement>();+ function visit(node: ts.Node) {+ if (ts.isJsxElement(node)) {+ const id = node.openingElement.attributes.properties.find(prop => ts.isJsxAttribute(prop) && prop.name.getText(source) === 'testID') as ts.JsxAttribute | undefined;+ if (id?.initializer && ts.isStringLiteral(id.initializer)) elements.set(id.initializer.text, node);+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+ const viewport = elements.get('session.bottomViewport')!;+ const layer = elements.get('session.bottomLayer')!;+ expect(layer.parent).toBe(viewport);+ expect(layer.openingElement.getText(source)).toContain('ref={bottomOverlayRef}');+ expect(viewport.openingElement.getText(source)).toContain('pointerEvents="box-none"');+ for (const component of ['SessionComposerPalette', 'ComposerActivityStatus', 'SessionComposerInput']) {+ expect(viewport.getText(source)).toContain('<' + component);+ }+ });+ // mobile-development.md: Metro-only manifest routing must not enter native fingerprint config.+ it('connects Metro manifest injection to runtime while keeping dev release routing outside production config', () => {+ const runtime = readFileSync(resolve(process.cwd(), 'src/config/env.ts'), 'utf8');+ const config = readFileSync(resolve(process.cwd(), 'app.config.js'), 'utf8');+ expect(runtime).toContain('process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL');+ expect(config).toContain("...(region === 'dev'");+ expect(config).toContain('EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL:');+ expect(config).toContain("resolveManifestBaseUrl('cn')");+ expect(config).not.toContain('xdtProductionEnv: mobileBundleEnv');+ });+});++// guard: mobile-development.md Google Play install authority: all JS update entry points must honor it.+it('keeps content OTA independent while suppressing website APK checks on Google Play installs', () => {+const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');+expect(layout).toContain('const otaReady = useStartupOtaGate(channel);');+const settings = readFileSync(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');+expect(settings).toContain('isGooglePlayInstallation: playManagedUpdates,');+expect(settings).toContain('checkBundleUpdate: bundleCheckEnabled ? checkBundleUpdate : undefined,');+expect(settings).toContain('const updateCheckEnabled = bundleCheckEnabled || updatesEnabled;');+expect(settings).toContain("t('settings.version.googlePlayContentUpdateUnavailable')");+});++// guard: native persistent history hosts must wrap routes and replace route prefetch ownership.+describe('persistent native history ownership', () => {+ it('does not keep the old route preloading mechanism alongside the resident host', () => {+ const home = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');+ expect(home).not.toContain('useRecentTaskPreload');+ expect(home).not.toContain('router.prefetch');+ const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');+ // Source structure is independent of checkout line endings.+ for (const source of [layout.replace(/\r\n/g, '\n'), layout.replace(/\r?\n/g, '\r\n')]) {+ const provider = source.search(/<RecentMessageHistoriesProvider(?:\s|>)/);+ const residentProvider = source.indexOf('<ResidentHomeListProvider>');+ const stack = source.search(/<Stack\s/);+ expect(provider).toBeGreaterThanOrEqual(0);+ expect(residentProvider).toBeGreaterThan(provider);+ expect(stack).toBeGreaterThan(provider);+ expect(stack).toBeGreaterThan(residentProvider);+ expect(source.indexOf('</ResidentHomeListProvider>')).toBeGreaterThan(stack);+ expect(source.indexOf('</RecentMessageHistoriesProvider>')).toBeGreaterThan(+ source.indexOf('</ResidentHomeListProvider>'),+ );+ }+ });+});diff --git a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.tsindex 26108421b2..2f68ff3008 100644--- a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts+++ b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { requireNativeModule } from 'expo-modules-core';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -295,43 +293,4 @@ describe('mobileRealtimeAudio', () => {expect(shouldShowMobileVoiceUi('android')).toBe(true);});-- it('keeps the iOS native realtime recorder wired for interruption cleanup', () => {- const source = readFileSync(- resolve(process.cwd(), 'modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift'),- 'utf8',- );-- expect(source).toContain('AVAudioSession.interruptionNotification');- expect(source).toContain('AVAudioSession.routeChangeNotification');- expect(source).toContain('removeAudioSessionObservers()');- expect(source).toContain('handleAudioSessionInterruption');- expect(source).toContain('handleAudioRouteChange');- expect(source).toContain('OnAppEntersBackground');- expect(source).toContain('stopCapture(deactivateImmediately: true)');- expect(source).toContain('stopCapture()');- expect(source).toContain('unsignedIntegerValue(notification.userInfo?[AVAudioSessionInterruptionTypeKey])');- expect(source).toContain('unsignedIntegerValue(notification.userInfo?[AVAudioSessionRouteChangeReasonKey])');- });-- it('cancels voice runs in both composers when the app enters the background', () => {- const newSessionSource = readFileSync(- resolve(process.cwd(), 'app/sessions/new.tsx'),- 'utf8',- );- const existingSessionSource = readFileSync(- resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),- 'utf8',- );-- for (const source of [newSessionSource, existingSessionSource]) {- expect(source).toContain("AppState.addEventListener('change'");- expect(source).toContain("nextState !== 'background'");- expect(source).toContain('voiceControllerSessionRef.current = null');- expect(source).toContain('discardPendingPrewarm()');- expect(source).not.toContain("setAudioModeAsync");- }- expect(newSessionSource).toContain('cancelVoiceForDeviceSwitch();');- expect(existingSessionSource).toContain('cancelVoiceForAppBackground();');- });});diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.tsindex 503460a13d..c573abc253 100644--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { RemoteMessage, RemoteSession } from '@/session/types';@@ -380,13 +378,6 @@ describe('mobileSessionMessageCache', () => {await expect(getCachedSessionMessages('host-a', 'session-1')).resolves.toEqual([]);});- it('does not treat an empty in-memory render snapshot as a cache deletion', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');- expect(source).toContain('空内存可能只是 regular LRU 淘汰');- expect(source).toContain('if (messages.length === 0) return;');- expect(source).toContain("if (retentionForSession(sessionId) === 'schedule')");- });-it('clears every cached session on logout but leaves unrelated keys', async () => {const { __testing, cacheSessionMessages, clearCachedSessionMessages, getCachedSessionMessages } =await import('@/session/mobileSessionMessageCache');diff --git a/apps/mobile/src/__tests__/mobileSimSource.test.ts b/apps/mobile/src/__tests__/mobileSimSource.test.tsindex 4fee943531..06213b8f53 100644--- a/apps/mobile/src/__tests__/mobileSimSource.test.ts+++ b/apps/mobile/src/__tests__/mobileSimSource.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, posix, win32 } from 'node:path';import {@@ -153,11 +153,6 @@ describe('mobile simulator Metro takeover', () => {);});- it('normalizes the Windows owner metadata cwd to the mobile directory', () => {- const source = readFileSync(join(process.cwd(), 'scripts/sim-metro.mjs'), 'utf8');- expect(source).toContain("cwd: owner.worktreeRoot ? join(owner.worktreeRoot, 'apps/mobile') : null");- });-it('falls back to the listener PID when the group is unavailable', async () => {const run = vi.fn();const stopped = await terminateMetro(123, {diff --git a/apps/mobile/src/__tests__/mobileVoiceScriptRedaction.test.ts b/apps/mobile/src/__tests__/mobileVoiceScriptRedaction.test.tsindex d243919181..3057d33f69 100644--- a/apps/mobile/src/__tests__/mobileVoiceScriptRedaction.test.ts+++ b/apps/mobile/src/__tests__/mobileVoiceScriptRedaction.test.ts@@ -1,7 +1,10 @@import { spawn } from 'node:child_process';import { createServer, type Server } from 'node:http';import { once } from 'node:events';-import { afterEach, describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import { afterEach, describe, expect, it, vi } from 'vitest';const startedServers: Server[] = [];@@ -10,6 +13,37 @@ afterEach(async () => {});describe('mobile voice script redaction', () => {+ // credentials-and-local-storage.md: checking configuration must not send+ // credentials or audio to a cloud endpoint until the explicit --run action.+ // The failure-redaction test below runs with --run and cannot protect this gate.+ it('keeps cloud preflight dry-run offline and hides its configured key', async () => {+ const source = readFileSync(resolve(process.cwd(), 'scripts/mobile-voice-cloud-preflight.mjs'), 'utf8');+ const start = source.indexOf('const DEFAULT_ASR_ENDPOINT =');+ if (start < 0) throw new Error('Cloud preflight workflow entry was not found');+ const secret = 'sk-preflight/dry run secret';+ const fetch = vi.fn(() => { throw new Error('Unexpected cloud HTTP request'); });+ const WebSocket = vi.fn(function () { throw new Error('Unexpected cloud WebSocket request'); });+ const log = vi.fn();+ const execution = runInNewContext('(async () => { ' + source.slice(start) + ' })()', {+ mobileRoot: '/fixture/mobile', resolve, URL, fetch, WebSocket,+ existsSync: () => false,+ readFileSync: () => { throw new Error('Unexpected credential or environment file read'); },+ console: { log, warn: log, error: log },+ process: {+ argv: ['node', 'mobile-voice-cloud-preflight.mjs'],+ env: { XDT_MOBILE_VOICE_PROXY_BASE_URL: 'https://voice.invalid', XDT_MOBILE_VOICE_PROXY_API_KEY: secret },+ exit: (code: number) => { throw new Error('preflight-exit:' + code); },+ },+ });+ await expect(execution).rejects.toThrow('preflight-exit:0');+ expect(fetch).not.toHaveBeenCalled();+ expect(WebSocket).not.toHaveBeenCalled();+ const output = log.mock.calls.map(call => call.join(' ')).join(String.fromCharCode(10));+ expect(output).toContain('dry run passed; add --run to call the cloud endpoints');+ expect(output).not.toContain(secret);+ expect(output).not.toContain(encodeURIComponent(secret));+ });+it('redacts synced voice keys from cloud preflight failure output', async () => {const secret = 'sk-script/redact secret';const server = createServer((_request, response) => {diff --git a/apps/mobile/src/__tests__/mobileXcode.test.ts b/apps/mobile/src/__tests__/mobileXcode.test.tsindex 15af1119b5..6f68f763d6 100644--- a/apps/mobile/src/__tests__/mobileXcode.test.ts+++ b/apps/mobile/src/__tests__/mobileXcode.test.ts@@ -1,8 +1,10 @@// @ts-nocheck —— 被测对象是 .mjs 开发工具模块,vitest 跑其纯函数。import { readFileSync } from 'node:fs';import { join, resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { runInNewContext } from 'node:vm';+import { describe, expect, it, vi } from 'vitest';import {+ mobileXcodeGeneratedDir,parseMobileXcodeArgs,selectMobileXcodeWorkspace,updateMobileXcodeEnvContent,@@ -11,6 +13,8 @@ import {extractMobileDevRegionArgs,withLocalMobileRegionConfig,} from '../../scripts/lib/mobile-dev-region.mjs';+import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';+import { resolvePnpmInvocation, usablePnpmExecPath } from '../../../../scripts/shared/pnpm-invocation.mjs';describe('mobile:xcode 参数', () => {it('不传 region 时默认 global', () => {@@ -46,10 +50,26 @@ describe('mobile simulator region 参数', () => {expect(() => extractMobileDevRegionArgs(['--region=cn', '--region=global'])).toThrow(/只能传一次/);});- it('把所选 region 直接注入 Metro 子进程,不被 shell 残留值覆盖', () => {+ it.each(['global', 'cn'])('把所选 %s 注入 Metro 子进程,覆盖 shell 残留值', async (region) => {const source = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');- expect(source).toContain('const buildEnv = withLocalMobileRegionConfig(');- expect(source).toContain('...process.env,\n ...buildEnv,');+ const start = source.indexOf("const args = ['exec', 'expo', 'start'");+ if (start < 0) throw new Error('Missing sim:start launch flow');+ const buildEnv = withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region }));+ const spawn = vi.fn(() => ({ once: vi.fn(), on: vi.fn() }));+ await runInNewContext(`(async () => { ${source.slice(start)} })()`, {+ DEFAULT_PORT: 8081, portArgs: { port: 8082, passthrough: [] },+ portInUse: async () => false, ensureAndroidTarget: vi.fn(), spawn,+ console: { log: vi.fn(), error: vi.fn() },+ process: { env: { KEEP: 'inherited', EXPO_PUBLIC_CINDY_AUTH_REGION: region === 'cn' ? 'global' : 'cn',+ CINDY_USE_LOCAL_REGION_CONFIG: '0', EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://stale.invalid' } },+ resolvePnpmInvocation: (args, options) => resolvePnpmInvocation(args, { ...options, platform: 'darwin', execPath: '/node' }),+ usablePnpmExecPath, existsSync: () => false,+ mobileDir: '/repo/apps/mobile', worktreeRoot: '/repo', buildEnv, region,+ branch: 'test', commit: '123', sourceIdentity: 'test@123',+ });+ expect(spawn).toHaveBeenCalledWith('pnpm', ['exec', 'expo', 'start', '--dev-client', '--port', '8082'],+ expect.objectContaining({ shell: false, env: expect.objectContaining({ ...buildEnv,+ KEEP: 'inherited', EXPO_PUBLIC_CINDY_AUTH_REGION: region, CINDY_USE_LOCAL_REGION_CONFIG: '1' }) }));});it('所有本地构建环境都启用 region JSON 配置源', () => {@@ -106,10 +126,64 @@ describe('mobile:xcode workspace 选择', () => {});describe('mobile:xcode 完整开发链路', () => {- it('打开 Xcode 后复用 sim:start 启动带 worktree/port 防护的 Metro', () => {+ // Execute main with only filesystem/process boundaries injected. The former+ // source checks could not prove that region survives the Xcode-to-Metro bridge+ // or that an occupied 8081 refuses before changing the generated project.+ it.each([+ { name: 'defaults to global despite a stale cn shell', argv: [], region: 'global', owner: 'free', sameEnv: false },+ { name: 'forwards explicit cn', argv: ['--region=cn'], region: 'cn', owner: 'free', sameEnv: false },+ { name: 'reuses the same checkout and region', argv: ['--region=cn'], region: 'cn', owner: 'local', sameEnv: true },+ { name: 'refuses another checkout', argv: [], region: 'global', owner: 'foreign', sameEnv: true, error: '其它 checkout/process' },+ { name: 'refuses a local Metro with changed region', argv: [], region: 'global', owner: 'local', sameEnv: false, error: 'region/env 将变化' },+ ])('$name', async ({ argv, region, owner, sameEnv, error }) => {const source = readFileSync(resolve(process.cwd(), 'scripts/open-ios-xcode.mjs'), 'utf8');- expect(source).toContain("resolve(mobileDir, 'scripts/sim-start.mjs')");- expect(source).toContain('await portInUse(metroPort)');- expect(source).toContain('execFileSync(process.execPath, [simStartPath, `--region=${args.region}`]');+ const start = source.indexOf('const iosDir =');+ const end = source.lastIndexOf('\nmain().catch(');+ if (start < 0 || end < start) throw new Error('Missing mobile:xcode main flow');+ const worktreeRoot = resolve('/fixture-xcode');+ const mobileDir = join(worktreeRoot, 'apps', 'mobile');+ const iosDir = join(mobileDir, 'ios');+ const envPath = join(mobileDir, '.env');+ const simStartPath = join(mobileDir, 'scripts', 'sim-start.mjs');+ const buildEnv = withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region }));+ const previousEnv = updateMobileXcodeEnvContent('', sameEnv ? buildEnv+ : withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region === 'cn' ? 'global' : 'cn' })));+ const files = new Map([[envPath, previousEnv]]);+ const writeFileSync = vi.fn((target, content) => files.set(target, content));+ const execFileSync = vi.fn();+ const podInstallBounded = vi.fn(async () => {});+ const portInUse = vi.fn(async () => owner !== 'free');+ const execution = runInNewContext(`(async () => { ${source.slice(start, end)}; await main(); })()`, {+ mobileDir, worktreeRoot, resolve,+ process: { platform: 'darwin', execPath: '/fixture-node', argv: ['node', 'open-ios-xcode.mjs', ...argv],+ env: { EXPO_PUBLIC_CINDY_AUTH_REGION: region === 'cn' ? 'global' : 'cn', KEEP: 'inherited' } },+ console: { log: vi.fn() },+ parseMobileXcodeArgs, withLocalMobileRegionConfig, mobileClientBundleEnv, updateMobileXcodeEnvContent,+ existsSync: (target) => files.has(target), readFileSync: (target) => files.get(target), writeFileSync,+ portInUse, listenerPid: () => '4242', cwdOfPid: () => owner === 'local' ? mobileDir : resolve('/other-checkout/apps/mobile'),+ isInside: (root, cwd) => cwd === mobileDir && root === worktreeRoot,+ execFileSync, podInstallBounded, readdirSync: () => ['Pods.xcworkspace', 'Cindy.xcworkspace'],+ selectMobileXcodeWorkspace, mobileXcodeGeneratedDir,+ });+ if (error) {+ await expect(execution).rejects.toThrow(error);+ expect(execFileSync).not.toHaveBeenCalled();+ expect(podInstallBounded).not.toHaveBeenCalled();+ expect(writeFileSync).not.toHaveBeenCalled();+ expect(files.get(envPath)).toBe(previousEnv);+ } else {+ await execution;+ const expectedEnv = expect.objectContaining({ ...buildEnv, KEEP: 'inherited', EXPO_PUBLIC_CINDY_AUTH_REGION: region });+ expect(execFileSync).toHaveBeenNthCalledWith(1, 'pnpm', ['exec', 'expo', 'prebuild', '-p', 'ios', '--clean', '--no-install'],+ { cwd: mobileDir, env: expectedEnv, stdio: 'inherit' });+ expect(podInstallBounded).toHaveBeenCalledWith({ iosDir, env: expectedEnv });+ expect(execFileSync).toHaveBeenNthCalledWith(2, 'open', ['-a', 'Xcode', join(iosDir, 'Cindy.xcworkspace')],+ { cwd: mobileDir, stdio: 'inherit' });+ expect(execFileSync).toHaveBeenNthCalledWith(3, '/fixture-node', [simStartPath, `--region=${region}`],+ { cwd: worktreeRoot, env: expectedEnv, stdio: 'inherit' });+ expect(files.get(envPath)).toBe(updateMobileXcodeEnvContent(previousEnv, buildEnv));+ expect(writeFileSync).toHaveBeenCalledTimes(sameEnv ? 0 : 1);+ }+ expect(portInUse).toHaveBeenCalledWith(8081);});});diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.tsindex b60c1a61e6..86d1a2599c 100644--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts@@ -147,13 +147,6 @@ describe('mobile native app config', () => {expect(cn.extra.xdtProductionEnv).not.toHaveProperty('EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',);- const runtimeEnvSource = readFileSync(- resolve(process.cwd(), 'src/config/env.ts'),- 'utf8',- );- expect(runtimeEnvSource).toContain(- 'process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',- );});it('keeps the CN Release manifest injection CindyDev-only and outside Expo config', () => {@@ -161,19 +154,6 @@ describe('mobile native app config', () => {readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),);const buildConfig = require(resolve(process.cwd(), 'app.config.js'));- const appConfigSource = readFileSync(- resolve(process.cwd(), 'app.config.js'),- 'utf8',- );-- expect(appConfigSource).toContain("...(region === 'dev'");- expect(appConfigSource).toContain(- 'EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL:',- );- expect(appConfigSource).toContain("resolveManifestBaseUrl('cn')");- expect(appConfigSource).not.toContain(- 'xdtProductionEnv: mobileBundleEnv',- );process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'cn';process.env.EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL =@@ -649,14 +629,10 @@ describe('mobile native app config', () => {});it('keeps Metro React resolution on the mobile app dependency', () => {- const metroConfig = readFileSync(- resolve(process.cwd(), 'metro.config.js'),- 'utf8',- );- expect(metroConfig).toContain("react: path.join(appNodeModules, 'react')");- expect(metroConfig).not.toContain("react: path.join(workspaceNodeModules, 'react')");- expect(metroConfig).toContain("'auth-client'");- expect(metroConfig).toContain("'@cindy/device-link-protocol'");+ const metroConfigPath = require.resolve('../../metro.config.js');+ const metroConfig = require(metroConfigPath);+ expect(metroConfig.resolver.extraNodeModules.react).toBe(join(dirname(metroConfigPath), 'node_modules', 'react'));+ expect(metroConfig.resolver.extraNodeModules['@cindy/device-link-protocol']).toBe(resolve(dirname(metroConfigPath), '../../packages/device-link-protocol'));});it('Metro nodeModulesPaths 覆盖 workspace TS 源码包各自的 node_modules(pnpm hoisted 布局下 workspace: 链接不提升到根,只在消费方包自己的 node_modules)', () => {@@ -679,103 +655,6 @@ describe('mobile native app config', () => {expect(paths[1]).toBe(join(resolve(appDir, '../..'), 'node_modules'));});- it('wires first-party Apple, public Google, and the minimal official WeChat bridge', () => {- const appJson = JSON.parse(- readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),- );- const packageJson = JSON.parse(- readFileSync(resolve(process.cwd(), 'package.json'), 'utf8'),- );- const configSource = readFileSync(- resolve(process.cwd(), 'app.config.js'),- 'utf8',- );- const pluginSource = readFileSync(- resolve(process.cwd(), 'modules/xdt-wechat-login/plugin/index.js'),- 'utf8',- );- const iosPodspec = readFileSync(- resolve(- process.cwd(),- 'modules/xdt-wechat-login/ios/XdtWechatLogin.podspec',- ),- 'utf8',- );- const androidGradle = readFileSync(- resolve(process.cwd(), 'modules/xdt-wechat-login/android/build.gradle'),- 'utf8',- );- const moduleConfig = readFileSync(- resolve(- process.cwd(),- 'modules/xdt-wechat-login/expo-module.config.json',- ),- 'utf8',- );- const iosCoordinator = readFileSync(- resolve(- process.cwd(),- 'modules/xdt-wechat-login/ios/XdtWechatAuthCoordinator.swift',- ),- 'utf8',- );- const iosWechatPodfilePlugin = readFileSync(- resolve(process.cwd(), 'plugins/with-wechat-opensdk-modulemap.js'),- 'utf8',- );- const iosSubscriber = readFileSync(- resolve(- process.cwd(),- 'modules/xdt-wechat-login/ios/XdtWechatLoginAppDelegateSubscriber.swift',- ),- 'utf8',- );-- expect(appJson.expo.ios.usesAppleSignIn).toBe(true);- expect(appJson.expo.plugins).toContain('expo-apple-authentication');- expect(packageJson.dependencies['expo-apple-authentication']).toBeTruthy();- expect(- packageJson.dependencies['@react-native-google-signin/google-signin'],- ).toBe('16.1.2');- expect(packageJson.dependencies['xdt-wechat-login']).toBe(- 'file:./modules/xdt-wechat-login',- );- expect(- existsSync(- resolve(- process.cwd(),- 'modules/xdt-feishu-login/expo-module.config.json',- ),- ),- ).toBe(false);- expect(configSource).toContain(- "'@react-native-google-signin/google-signin'",- );- expect(configSource).toContain("'xdt-wechat-login/plugin'");- expect(pluginSource).toContain("'weixinULAPI'");- expect(pluginSource).toContain("'.wxapi.WXEntryActivity'");- expect(pluginSource).toContain('withWechatEntryActivity(config, appId)');- expect(pluginSource).toContain('createWXAPI(this, ${kotlinAppId}, false)');- expect(iosPodspec).toContain("s.dependency 'WechatOpenSDK', '2.0.5'");- expect(androidGradle).toContain('wechat-sdk-android:6.8.38');- expect(moduleConfig).toContain('XdtWechatLoginAppDelegateSubscriber');- expect(iosCoordinator).toContain(- 'WXApi.handleOpenUniversalLink(userActivity, delegate: self)',- );- expect(iosCoordinator).toContain('#if targetEnvironment(simulator)');- expect(iosCoordinator).toContain('ERR_WECHAT_UNAVAILABLE_ON_SIMULATOR');- expect(iosWechatPodfilePlugin).toContain(- 'xdt-wechat-login: arm64 simulator stub linkage',- );- expect(iosWechatPodfilePlugin).toContain(- "other_linker_flags[:libraries].delete?('WechatOpenSDK')",- );- expect(iosWechatPodfilePlugin).toContain(- "OTHER_LDFLAGS[sdk=iphoneos*]",- );- expect(iosSubscriber).toContain('continue userActivity: NSUserActivity');- });-it('independently injects the WeChat simulator hook into an existing Podfile', () => {const plugin = require(resolve(process.cwd(), 'plugins/with-wechat-opensdk-modulemap.js'),diff --git a/apps/mobile/src/__tests__/nativeE2eContracts.test.ts b/apps/mobile/src/__tests__/nativeE2eContracts.test.tsnew file mode 100644index 0000000000..40679fa0e7--- /dev/null+++ b/apps/mobile/src/__tests__/nativeE2eContracts.test.ts@@ -0,0 +1,79 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++// guard: credentials-and-local-storage.md requires legacy keys to be removed at startup/logout.+// The storage unit suite tests actual deletion; this cross-module check prevents dropping AuthContext callers.+// mobile-development.md native boundary: Android must reuse shipped ExpoAudio, not add an unsupported recorder.+// Actual recording is covered in mobileRealtimeAudio; native registration cannot execute in a JS unit runner.+describe('native e2e security and native boundary contracts', () => {+it('clears local mobile voice credentials on logout and at auth startup', () => {+ const authContext = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');++ expect(authContext).toContain(+ "from '@/session/mobileVoiceCredentialStore'",+ );+ expect(authContext).toContain("from '@/session/mobileVoiceHistoryStore'");+ // BYOK/穿透存储模块已删除:清理统一收敛进 clearAllMobileVoiceCredentials+ // (含 serviceMode 与 LiteLLM key 的存量键)。+ expect(authContext).not.toContain('mobileVoiceLiteLlmSettings');+ expect(authContext).not.toContain('mobileVoiceServiceMode');+ expect(authContext).toContain(+ 'await clearAllMobileVoiceCredentials().catch(() => undefined);',+ );+ expect(authContext).toContain(+ 'await clearAllMobileVoiceInputHistories().catch(() => undefined);',+ );+ // Scope the ordering check to the shared local-session cleanup: both logout and confirmed+ // account deletion use it, and refresh-token deletion remains serialized against refresh.+ const cleanupStart = authContext.indexOf('const clearLocalSession = useCallback(async (');+ const cleanupBody = authContext.slice(cleanupStart, authContext.indexOf('}, [', cleanupStart));+ const refreshTokenDelete = cleanupBody.indexOf('await serializeRefreshTokenMutation(() =>');+ expect(refreshTokenDelete).toBeGreaterThanOrEqual(0);+ expect(cleanupBody).toContain('deleteSecureItem(AUTH_SESSION_KEY).catch(() => undefined)');+ expect(cleanupBody.indexOf('await clearAllMobileVoiceCredentials().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);+ expect(cleanupBody.indexOf('await clearAllMobileVoiceInputHistories().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);+ const logoutStart = authContext.indexOf('const logout = useCallback(async () => {');+ const logoutBody = authContext.slice(logoutStart, authContext.indexOf('}, [', logoutStart));+ expect(logoutBody).toContain('clearMobileLoginCredentialsForLogout({');+ expect(logoutBody).toContain(+ 'clearReceipt: () => persistAccountDeletionReceipt(null),',+ );+ expect(logoutBody).toContain(+ 'await clearLocalSession({ persistedAuthAlreadyCleared: true });',+ );+ // 启动(auth 初始化)也要做一次存量清理,防旧版本留下的桌面 key 继续躺在+ // secure storage(与 LEGACY_* token 清理同一批)。+ expect(authContext).toContain('clearAllMobileVoiceCredentials().catch(() => undefined),');+ });+it('backs Android realtime voice with the Expo AudioStream already shipped in the app', () => {+ const expoModuleConfig = readFileSync(+ resolve(process.cwd(), 'modules/xdt-mobile-realtime-audio/expo-module.config.json'),+ 'utf8',+ );+ const realtimeAudio = readFileSync(resolve(process.cwd(), 'src/session/mobileRealtimeAudio.ts'), 'utf8');+ const appJson = readFileSync(resolve(process.cwd(), 'app.json'), 'utf8');++ // The latency-tuned custom recorder stays Apple-only. Android reuses the+ // PCM SharedObject from expo-audio, which is already a native dependency.+ expect(expoModuleConfig).toContain('"platforms": ["apple"]');+ expect(expoModuleConfig).not.toContain('"android"');+ expect(appJson).toContain('"recordAudioAndroid": true');+ expect(realtimeAudio).toContain("requireNativeModule<ExpoAudioNativeModule>('ExpoAudio')");+ expect(realtimeAudio).toContain('new module.AudioStream({');+ expect(realtimeAudio).toContain("encoding: 'int16'");+ expect(realtimeAudio).toContain('convertExpoAudioPcm16(');+ expect(realtimeAudio).toContain("throw new UnavailabilityError('Cindy mobile voice input', 'realtime microphone PCM capture')");+ expect(realtimeAudio).toContain('EXPO_PUBLIC_XDT_MOBILE_E2E_MOCK_AUDIO');+ });++ // The old credential relay must not become reachable through a local developer command.+ it('keeps the retired voice credential relay out of developer entry points', () => {+ const scripts = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')).scripts;+ expect(Object.keys(scripts).some((key) => key.includes('voice:credential:') || ['test:voice-cloud:doctor', 'test:voice-cloud:device', 'test:voice-cloud:local-desktop-relay'].includes(key))).toBe(false);+ for (const file of ['scripts/local-device-link-smoke.mjs', 'scripts/mock-device-link-host.mjs']) {+ const source = readFileSync(resolve(process.cwd(), file), 'utf8');+ for (const removed of ['voiceCredentialOverride', 'loadVoiceCredentialOverride', '--voice-credential-file']) expect(source).not.toContain(removed);+ }+ });+});diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.tsindex 6d92b40d4b..2fd71e375c 100644--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts@@ -2,7 +2,8 @@ import { spawnSync } from 'node:child_process';import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { readSimEnvironment } from '../../scripts/lib/sim-environment.mjs';-import { resolve } from 'node:path';+import { posix, resolve } from 'node:path';+import ts from 'typescript';import { runInNewContext } from 'node:vm';import { describe, expect, it, vi } from 'vitest';@@ -26,7 +27,7 @@ describe('native e2e environment', () => {it.each([false, true])('preserves custom-port ownership when occupied=%s', async (occupied) => {const source = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');const start = source.indexOf("const args = ['exec', 'expo', 'start'");- expect(start).toBeGreaterThan(0);+ if (start < 0) throw new Error('script workflow entry missing');const exitCallbacks: Array<() => void> = [];const child = {pid: 4242,@@ -93,48 +94,6 @@ describe('native e2e environment', () => {expect(flow).toContain('id: "session.menuUsageRow"');expect(flow.indexOf('id: "session.menuUsageRow"')).toBeGreaterThan(flow.indexOf('id: "session.menuSheet"'));expect(flow).not.toContain('id: "session.usageButton"');- const menu = readFileSync(resolve(process.cwd(), 'src/session/SessionMenuSheet.tsx'), 'utf8');- expect(menu).toMatch(/<SessionUsageSummary[^>]+onPress=\{openInfo\}/);- });-- it('uses a Java 17 runtime for Maestro without requiring global shell changes', () => {- const helper = readFileSync(resolve(process.cwd(), 'scripts/java-runtime-env.mjs'), 'utf8');- const doctor = readFileSync(resolve(process.cwd(), 'scripts/native-e2e-doctor.mjs'), 'utf8');- const runner = readFileSync(resolve(process.cwd(), 'scripts/maestro-e2e.mjs'), 'utf8');-- expect(helper).toContain('const MIN_JAVA_MAJOR = 17');- expect(helper).toContain('env.ANDROID_STUDIO_JDK');- expect(helper).toContain("env.ProgramFiles, 'Android', 'Android Studio', 'jbr'");- expect(helper).toContain("brew', ['--prefix', 'openjdk@17']");- expect(helper).toContain("'/usr/libexec/java_home', ['-v', version]");- expect(helper).toContain('JAVA_HOME: javaHome');- expect(helper).toContain("PATH: [join(javaHome, 'bin'), baseEnv.PATH]");- expect(doctor).toContain("import { javaRuntimeDetail, resolveJavaRuntimeEnv } from './java-runtime-env.mjs';");- expect(doctor).toContain('const toolEnv = resolveJavaRuntimeEnv(process.env);');- expect(doctor).toContain("spawnSync('maestro', ['--version'], { encoding: 'utf8', env: toolEnv })");- expect(runner).toContain("import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';");- expect(runner).toContain('const toolEnv = resolveJavaRuntimeEnv(process.env);');- expect(runner).toContain('...toolEnv');- const simStart = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');- expect(simStart).toContain("import { readSimEnvironment } from './lib/sim-environment.mjs';");- expect(simStart).toContain('const { loginScenario, envFingerprint } = readSimEnvironment(mobileDir, buildEnv);');- expect(simStart).toContain('writeMetroOwner(portArgs.port, {');- expect(simStart).toContain("child.once('exit', () => clearMetroOwner(portArgs.port, child.pid));");- expect(simStart).not.toContain('writeMetroOwner(DEFAULT_PORT,');- expect(simStart).not.toContain('clearMetroOwner(DEFAULT_PORT,');- expect(runner).toContain("/(^|[\\\\/])login_mock(?:_no_clear)?\\.yaml$/");- expect(runner).toContain("process.env.XDT_MOBILE_E2E_EXPO_LAUNCH_DELAY_MS ?? '20000'");- expect(runner).toContain("process.env.XDT_MOBILE_E2E_EXPO_TERMINATE_BEFORE_OPEN ?? 'true'");- expect(runner).toContain("process.env.XDT_MOBILE_E2E_EXPO_OPEN_BEFORE_TEST ?? 'true'");- expect(runner).toContain("if (expoUrl && expoTerminateBeforeOpen === 'true') terminateExpoApp(platform);");- expect(runner).toContain('function terminateExpoApp(platform)');- expect(runner).toContain('function terminateApp(targetAppId, platform)');- expect(runner).toContain('function launchNativeApp(targetAppId, platform)');- expect(runner).toContain('terminateApp(appId, platform);');- expect(runner).toContain('launchNativeApp(appId, platform);');- expect(runner).toContain("MAESTRO_DRIVER_STARTUP_TIMEOUT: process.env.MAESTRO_DRIVER_STARTUP_TIMEOUT ?? '120000'");- expect(runner).toContain("`XDT_MOBILE_E2E_EXPO_URL=${expoUrl ?? ''}`");- expect(runner).toContain('sleepSync(expoLaunchDelayMs)');});it('opens the Expo target route before shared flows while cleaning native stale overlays', () => {@@ -177,97 +136,6 @@ describe('native e2e environment', () => {expect(visualOfflineFlow).not.toContain('session.collaborationReadOnlyComposer');});- it('can own the Expo lifecycle for iOS local runtime smoke', () => {- const packageJson = readFileSync(resolve(process.cwd(), 'package.json'), 'utf8');- const localSmoke = readFileSync(resolve(process.cwd(), 'scripts/local-device-link-smoke.mjs'), 'utf8');-- expect(packageJson).toContain('"test:e2e:local:ios"');- expect(packageJson).toContain('--start-server --start-expo --mock-host --profile ios-iphone-17-pro-expo-go');- expect(localSmoke).toContain("if (arg === '--start-expo')");- expect(localSmoke).toContain("if (arg === '--no-mock-audio')");- expect(localSmoke).toContain("const useMockAudio = voiceProxySelected && !options.noMockAudio;");- expect(localSmoke).toContain("if (arg === '--voice-cloud-preflight')");- expect(localSmoke).toContain("if (arg === '--voice-cloud-all-candidates')");- // 穿透 credential 工具族已随 device-link:voice:credential-sync 下线删除:- // smoke 不再有任何 voice credential fetch/override 面。- expect(localSmoke).not.toContain('voice-credential');- expect(localSmoke).not.toContain('voiceCredential');- expect(localSmoke).toContain('expectedControllableDeviceId: options.mockHost ? mockHostDeviceId : undefined');- expect(localSmoke).toContain('function isControllableDevice(device)');- expect(localSmoke).toContain('function runVoiceCloudPreflight()');- expect(localSmoke).toContain("...(options.voiceCloudAllCandidates ? ['--all-candidates'] : [])");- expect(localSmoke).toContain('preflightEnv.XDT_MOBILE_VOICE_PROXY_BASE_URL = voiceProxyBaseUrl;');- expect(localSmoke).toContain("preflightEnv.XDT_MOBILE_VOICE_PROXY_API_KEY = 'sk-mock-mobile-voice-key';");- expect(localSmoke).toContain('runNodeScript(voiceCloudPreflightScript, args, preflightEnv);');- expect(localSmoke).toContain('function startMockHostProcess(baseUrl, hostDeviceId, scenario, realDbPath)');- expect(localSmoke).toContain('await stopMockHost.ready;');- expect(localSmoke).toContain('mock host did not become ready within');- expect(localSmoke).toContain("line.includes('mock-device-link-host ready')");- expect(localSmoke).toContain('async function stopActiveMockHost()');- expect(localSmoke.indexOf('await stopActiveMockHost();')).toBeLessThan(- localSmoke.indexOf('if (options.mockHost) await cleanupE2eDeviceRecords(apiBase, mockHostDeviceId);'),- );- expect(localSmoke).toContain('async function startExpoProcess(url)');- expect(localSmoke).toContain('async function assertExpoReady(url');- expect(localSmoke).toContain('Expo Go native E2E needs Metro before Maestro opens the app.');- expect(localSmoke).toContain('EXPO_PUBLIC_XDT_API_BASE_URL: apiBase');- expect(localSmoke).toContain("&& (flowSuite === 'visual' || flowSuite === 'full' || flowSuite === 'file')");- expect(localSmoke).toContain("flowSuite === 'visual' ? `${mockHostDeviceId}-${flowSlug(flow)}` : mockHostDeviceId");- expect(localSmoke).toContain("if (flowSuite === 'full' && flow === 'fixture_controls_smoke.yaml') return 'controls';");- expect(localSmoke).toContain("if (suite === 'controls') return 'controls';");- });-- it('can run the iOS smoke against local desktop SQLite data without hardcoding a user path', () => {- const packageJson = readFileSync(resolve(process.cwd(), 'package.json'), 'utf8');- const mockHost = readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8');-- expect(packageJson).toContain('"test:e2e:local:real-db:ios"');- expect(packageJson).toContain('--mock-host-real-db auto');- expect(mockHost).toContain('function resolveRealDbPath(dbPath, Database)');- expect(mockHost).toContain("rawPath && rawPath !== 'auto'");- expect(mockHost).toContain("path.join(home, 'Library', 'Application Support', 'xdt-maker')");- expect(mockHost).toContain("path.join(appData, 'xdt-maker')");- expect(mockHost).toContain('--real-db auto could not find a readable XDMaker SQLite DB with sessions');- });-- it('keeps the mock host capable of exercising deferred session Agent switching', () => {- const mockHost = readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8');-- expect(mockHost).toContain("case 'maker:switch-session-agent':");- expect(mockHost).toContain("case 'maker:get-session-agent-switch-intent':");- expect(mockHost).toContain("case 'maker:provider:list':");- expect(mockHost).toContain('supportsSessionAgentSwitch: true');- expect(mockHost.indexOf('applyPendingAgentSwitchIntent(id);')).toBeLessThan(- mockHost.indexOf("const text = typeof queued?.text === 'string'"),- );- });-- it('keeps the mock host capable of exercising the native worktree two-step flow', () => {- const mockHost = readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8');-- for (const channel of [- 'maker:get-new-maker-defaults',- 'maker:apply-new-maker-worktree-pref',- 'worktree:detect-cwd',- 'worktree:list-branches',- 'worktree:suggest-name',- 'worktree:create',- 'worktree:discard-precreated',- ]) {- expect(mockHost).toContain(`case '${channel}':`);- }- expect(mockHost).toContain("const MOCK_WORKTREE_BRANCHES = ['main', 'feature/mobile-worktree', 'release/mobile'];");- expect(mockHost).toContain('supportsRecoveryKeyDiscard: true');- expect(mockHost).toContain('branches: [...mockWorktree.branches]');- expect(mockHost).toContain('current: mockWorktree.currentBranch');- expect(mockHost).toContain("path: path.join(normalizedBaseRepo, '.cindy-worktrees', name)");- expect(mockHost).toContain('branch: `xdt/${name}`');- expect(mockHost).toContain('sourceBranch,');- expect(mockHost).toContain('worktreePath: claimedWorktree?.meta.path ?? null');- expect(mockHost).toContain("throw mockIpcError('PRECONDITION_FAILED', '会话已认领该 worktree,拒绝补偿回收')");- expect(mockHost).toContain('return { discarded: true, branchDeleted: true };');- });-it('keeps the reconnect entry usable without the removed server and auth APIs', () => {const script = 'scripts/device-link-reconnect-smoke.mjs';const packageJson = readFileSync(resolve(process.cwd(), 'package.json'), 'utf8');@@ -278,7 +146,6 @@ describe('native e2e environment', () => {expect(result.status).toBe(0);expect(result.stdout).toContain('formal DeviceLinkClient');expect(result.stdout).toContain('loopback WebSocket contract fixture');- expect(readFileSync(resolve(process.cwd(), script), 'utf8')).not.toContain('/api/auth/dev-login');const missingCredentials = spawnSync(process.execPath, [script, '--interop'], {cwd: process.cwd(), encoding: 'utf8', timeout: 10_000,@@ -296,7 +163,7 @@ describe('native e2e environment', () => {it.each([true, false])('probes Java only for real Maestro runs (dryRun=%s)', (dryRun) => {const source = readFileSync(resolve(process.cwd(), 'scripts/maestro-e2e.mjs'), 'utf8');const start = source.indexOf('const options = parseArgs(');- expect(start).toBeGreaterThan(0);+ if (start < 0) throw new Error('script workflow entry missing');const resolveJavaRuntimeEnv = vi.fn(() => { throw new Error('java-probe'); });const probeMetroOwnership = vi.fn();const spawn = vi.fn();@@ -331,149 +198,145 @@ describe('native e2e environment', () => {expect(result.stdout).toContain('maestro dry run: APP_ID=');expect(result.stderr).not.toContain('Active Metro');});+});- it('keeps cloud voice preflight opt-in and secret-redacted with the credential relay removed', () => {- const packageJson = readFileSync(resolve(process.cwd(), 'package.json'), 'utf8');- const preflight = readFileSync(resolve(process.cwd(), 'scripts/mobile-voice-cloud-preflight.mjs'), 'utf8');- const mockVoiceProxy = readFileSync(resolve(process.cwd(), 'scripts/mock-voice-proxy.mjs'), 'utf8');- const mockHost = readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8');- const readme = readFileSync(resolve(process.cwd(), 'README.md'), 'utf8');-- expect(packageJson).toContain('"test:voice-cloud:preflight": "node scripts/mobile-voice-cloud-preflight.mjs"');- expect(packageJson).toContain('"test:voice-cloud:preflight:run": "node scripts/mobile-voice-cloud-preflight.mjs --run"');- // 穿透 credential 工具族(export/fetch/relay smoke/doctor/device gate)已随- // device-link:voice:credential-sync 下线一并删除,不能再出现在 package scripts 里。- expect(packageJson).not.toContain('voice:credential:');- expect(packageJson).not.toContain('test:voice-cloud:doctor');- expect(packageJson).not.toContain('test:voice-cloud:local-desktop-relay');- expect(packageJson).not.toContain('test:voice-cloud:device');- expect(preflight).toContain('dry run passed; add --run to call the cloud endpoints');- expect(preflight).toContain('XDT_MOBILE_VOICE_CREDENTIAL_JSON');- expect(preflight).toContain('XDT_MOBILE_VOICE_PROXY_API_KEY');- expect(preflight).toContain('XDT_MOBILE_VOICE_PREFLIGHT_ALL_CANDIDATES');- expect(preflight).toContain("if (arg === '--all-candidates')");- expect(preflight).toContain('async function preflightAsrCandidates');- expect(preflight).toContain('async function preflightRefinerCandidates');- expect(preflight).toContain("credentialAsrChain(credential).slice(0, 1)");- expect(preflight).toContain("credentialRefinerChain(credential).slice(0, 1)");- expect(preflight).toContain('mobileRealtimeAsrUnsupportedReason');- expect(preflight).toContain('asr.mode is not supported for mobile realtime preflight');- expect(preflight).toContain("validateProviderChain(credential, 'asrProviderChain'");- expect(preflight).toContain("validateProviderChain(credential, 'refinerProviderChain'");- expect(preflight).toContain('function credentialAsrChain(credential)');- expect(preflight).toContain('function credentialRefinerChain(credential)');- expect(preflight).toContain("const primary = normalized.split(/[-_]/)[0];");- expect(preflight).toContain("case 'mandarin':");- expect(preflight).toContain('function redactionCandidates(secret)');- expect(preflight).not.toContain('console.log(credential.proxyApiKey');- expect(preflight).not.toContain('console.warn(credential.proxyApiKey');- expect(preflight).not.toContain('console.error(credential.proxyApiKey');- expect(readme).toContain('--voice-cloud-all-candidates');- expect(readme).toContain('VOICE_CREDENTIAL_SYNC_REMOVED');- expect(readme).not.toContain('voice:credential:');- expect(readme).not.toContain('test:voice-cloud:doctor');- expect(readme).not.toContain('test:voice-cloud:device');- expect(mockVoiceProxy).toContain("url.pathname !== '/dashscope/api-ws/v1/realtime'");- // mock host 与 desktop dispatch 语义对齐:credential-sync 一律返回下线错误,- // 不再存在 mock 凭证或 credential override 面。- expect(mockHost).toContain("case 'device-link:voice:credential-sync':");- expect(mockHost).toContain("err.code = 'VOICE_CREDENTIAL_SYNC_REMOVED';");- expect(mockHost).toContain('手机语音输入已改用 Cindy 官方语音服务,请升级手机版。');- expect(mockHost).not.toContain('mockVoiceCredential');- expect(mockHost).not.toContain('voiceCredentialOverride');- expect(mockHost).not.toContain('loadVoiceCredentialOverride');- expect(mockHost).not.toContain("'--voice-credential-file'");- expect(mockHost).toContain("case 'device-link:voice:dictionary-learning':");- expect(mockHost).toContain("ignoreReason: 'mock-host'");+// These execute existing developer entry points; the old shape-only checks could pass+// while process environments, deferred switching, or recovery ownership were broken.+function scriptBody(file: string, entry: string) {+ const source = readFileSync(resolve(process.cwd(), file), 'utf8');+ const start = source.indexOf(entry);+ if (start < 0) throw new Error(`missing workflow entry: ${file}`);+ return source.slice(start);+}++const maestroBody = scriptBody('scripts/maestro-e2e.mjs', 'const options = parseArgs(');+const mockHostAst = ts.createSourceFile('mock-host.mjs', readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);+const mockHostFunctions = mockHostAst.statements.filter((node) => ts.isFunctionDeclaration(node) && !['broadcast', 'push', 'send'].includes(node.name?.text ?? '')).map((node) => node.getText(mockHostAst)).join(String.fromCharCode(10));+const mockBranches = mockHostAst.statements.find((node) => ts.isVariableStatement(node) && node.declarationList.declarations.some((decl) => ts.isIdentifier(decl.name) && decl.name.text === 'MOCK_WORKTREE_BRANCHES'))?.getText(mockHostAst);+if (!mockBranches) throw new Error('mock-host branch fixture missing');++function mockHost(platform: 'darwin' | 'win32' = 'darwin') {+ const state = {+ sessions: [{ id: 'session', agentKind: 'cc', model: 'old', workingDir: '/repo' }],+ messages: new Map(), projections: new Map(),+ };+ const send = vi.fn();+ const context = {+ state, sessionId: 'session', path: posix, revokedControllers: new Set(),+ broadcast: send, push: send, send, debug: false, console,+ process: { platform, env: { HOME: '/fixture-home', APPDATA: '/fixture-appdata' } },+ fs: { readdirSync: () => ['xdt-maker-test.db', 'unrelated.txt'], statSync: () => ({ mtimeMs: 1 }) },+ };+ return runInNewContext(`${mockBranches}+${mockHostFunctions}+const mockWorktree = createMockWorktreeState(state);+({ invoke: (channel, args) => handleInvoke(null, channel, args), state, listRealDbCandidates, resolveRealDbPath });`, context) as {+ invoke: (channel: string, args: unknown[]) => Promise<any>;+ state: typeof state; listRealDbCandidates: () => string[]; resolveRealDbPath: (path: string, Database: unknown) => string;+ };+}++describe('native e2e developer workflows', () => {+ it.each(['com.xd.cindy', 'host.exp.Exponent'])('passes Java env to doctor and Maestro after opening %s', (appId) => {+ const spawn = vi.fn((_command: string, _args: string[], _options: object) => ({ status: 0, stdout: '', stderr: '' }));+ const toolEnv = { JAVA_HOME: '/jdk17', PATH: '/jdk17/bin:/tools' };+ runInNewContext(maestroBody, {+ resolve: posix.resolve, existsSync: () => true, readFileSync: () => 'appId: test',+ resolveJavaRuntimeEnv: () => toolEnv, probeMetroOwnership: vi.fn(), spawnSync: spawn,+ resolveMobileE2eProfile: () => undefined, mobileRoot: '/mobile', flowRoot: '/mobile/flows',+ doctorScript: '/mobile/doctor.mjs', defaultAppId: 'com.xd.cindy', loginScenario: 'providers:email-only',+ console: { log: vi.fn() }, URL,+ process: {+ argv: ['node', 'maestro-e2e.mjs', '--platform', 'ios', '--app-id', appId],+ execPath: '/node', platform: 'darwin', env: { XDT_MOBILE_E2E_EXPO_LAUNCH_DELAY_MS: '0' },+ exit: (code: number) => { throw new Error(`exit:${code}`); },+ },+ });+ expect(spawn).toHaveBeenCalledWith('/node', expect.arrayContaining(['/mobile/doctor.mjs', '--require-maestro', '--platform', 'ios', '--app-id', appId]), { cwd: '/mobile', env: toolEnv, stdio: 'inherit' });+ expect(spawn).toHaveBeenLastCalledWith('maestro', expect.arrayContaining(['test', `APP_ID=${appId}`, `CLEAR_STATE=${appId === 'host.exp.Exponent' ? 'false' : 'true'}`]), expect.objectContaining({ env: expect.objectContaining({ ...toolEnv, MAESTRO_DRIVER_STARTUP_TIMEOUT: '120000' }) }));+ const commands = spawn.mock.calls.map(([command, args]) => `${command} ${args.join(' ')}`);+ const terminate = commands.findIndex((cmd) => cmd.includes(`terminate booted ${appId}`));+ const launch = commands.findIndex((cmd) => cmd.includes(appId === 'host.exp.Exponent' ? 'openurl booted exp://localhost:8081/--/devices' : `launch booted ${appId}`));+ expect(terminate).toBeGreaterThanOrEqual(0);+ expect(launch).toBeGreaterThan(terminate);+ expect(launch).toBeLessThan(commands.length - 1);});- it('clears local mobile voice credentials on logout and at auth startup', () => {- const authContext = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');-- expect(authContext).toContain(- "from '@/session/mobileVoiceCredentialStore'",- );- expect(authContext).toContain("from '@/session/mobileVoiceHistoryStore'");- // BYOK/穿透存储模块已删除:清理统一收敛进 clearAllMobileVoiceCredentials- // (含 serviceMode 与 LiteLLM key 的存量键)。- expect(authContext).not.toContain('mobileVoiceLiteLlmSettings');- expect(authContext).not.toContain('mobileVoiceServiceMode');- expect(authContext).toContain(- 'await clearAllMobileVoiceCredentials().catch(() => undefined);',- );- expect(authContext).toContain(- 'await clearAllMobileVoiceInputHistories().catch(() => undefined);',- );- // Scope the ordering check to the shared local-session cleanup: both logout and confirmed- // account deletion use it, and refresh-token deletion remains serialized against refresh.- const cleanupStart = authContext.indexOf('const clearLocalSession = useCallback(async (');- const cleanupBody = authContext.slice(cleanupStart, authContext.indexOf('}, [', cleanupStart));- const refreshTokenDelete = cleanupBody.indexOf('await serializeRefreshTokenMutation(() =>');- expect(refreshTokenDelete).toBeGreaterThanOrEqual(0);- expect(cleanupBody).toContain('deleteSecureItem(AUTH_SESSION_KEY).catch(() => undefined)');- expect(cleanupBody.indexOf('await clearAllMobileVoiceCredentials().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);- expect(cleanupBody.indexOf('await clearAllMobileVoiceInputHistories().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);- const logoutStart = authContext.indexOf('const logout = useCallback(async () => {');- const logoutBody = authContext.slice(logoutStart, authContext.indexOf('}, [', logoutStart));- expect(logoutBody).toContain('clearMobileLoginCredentialsForLogout({');- expect(logoutBody).toContain(- 'clearReceipt: () => persistAccountDeletionReceipt(null),',- );- expect(logoutBody).toContain(- 'await clearLocalSession({ persistedAuthAlreadyCleared: true });',- );- // 启动(auth 初始化)也要做一次存量清理,防旧版本留下的桌面 key 继续躺在- // secure storage(与 LEGACY_* token 清理同一批)。- expect(authContext).toContain('clearAllMobileVoiceCredentials().catch(() => undefined),');+ it('plans local Expo, mock host, real-db, and optional cloud preflight without starting them', () => {+ const result = spawnSync(process.execPath, ['scripts/local-device-link-smoke.mjs', '--dry-run', '--start-server', '--start-expo', '--mock-host', '--mock-host-real-db', 'auto', '--voice-cloud-preflight', '--voice-cloud-all-candidates', '--profile', 'ios-iphone-17-pro-expo-go'], {+ cwd: process.cwd(), encoding: 'utf8', timeout: 10_000,+ env: { ...process.env, EXPO_PUBLIC_LOGIN_SCENARIO: 'providers:email-only' },+ });+ expect(result.error).toBeUndefined();+ expect(result.status).toBe(0);+ expect(result.stdout).toContain('- start expo: yes');+ expect(result.stdout).toContain('- mock host real db: auto');+ expect(result.stdout).toContain('- voice cloud candidates: all ASR/refine provider candidates');+ expect(result.stdout).toContain('- expo login scenario: providers:email-only');});- it('backs Android realtime voice with the Expo AudioStream already shipped in the app', () => {- const expoModuleConfig = readFileSync(- resolve(process.cwd(), 'modules/xdt-mobile-realtime-audio/expo-module.config.json'),- 'utf8',- );- const realtimeAudio = readFileSync(resolve(process.cwd(), 'src/session/mobileRealtimeAudio.ts'), 'utf8');- const appJson = readFileSync(resolve(process.cwd(), 'app.json'), 'utf8');-- // The latency-tuned custom recorder stays Apple-only. Android reuses the- // PCM SharedObject from expo-audio, which is already a native dependency.- expect(expoModuleConfig).toContain('"platforms": ["apple"]');- expect(expoModuleConfig).not.toContain('"android"');- expect(appJson).toContain('"recordAudioAndroid": true');- expect(realtimeAudio).toContain("requireNativeModule<ExpoAudioNativeModule>('ExpoAudio')");- expect(realtimeAudio).toContain('new module.AudioStream({');- expect(realtimeAudio).toContain("encoding: 'int16'");- expect(realtimeAudio).toContain('convertExpoAudioPcm16(');- expect(realtimeAudio).toContain("throw new UnavailabilityError('Cindy mobile voice input', 'realtime microphone PCM capture')");- expect(realtimeAudio).toContain('EXPO_PUBLIC_XDT_MOBILE_E2E_MOCK_AUDIO');+ it.each(['darwin', 'win32'] as const)('discovers local SQLite candidates read-only for %s', (platform) => {+ const host = mockHost(platform);+ const candidates = host.listRealDbCandidates();+ expect(candidates).toHaveLength(3);+ expect(candidates[0]).toBe(`${platform === 'darwin' ? '/fixture-home/Library/Application Support' : '/fixture-appdata'}/xdt-maker/xdt-maker-test.db`);+ const close = vi.fn();+ const Database = vi.fn(function (_path: string, options: object) {+ expect(options).toEqual({ readonly: true, fileMustExist: true });+ return { pragma: vi.fn(), prepare: () => ({ get: () => ({ count: 1 }) }), close };+ });+ expect(host.resolveRealDbPath('auto', Database)).toBe(candidates[0]);+ expect(Database).toHaveBeenCalledTimes(3);+ expect(close).toHaveBeenCalledTimes(3);});- it('sends the realtime voice draft returned by the controller instead of stale React state', () => {- const sessionScreen = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');+ it('applies a deferred Agent switch only when the next queued message is accepted', async () => {+ const host = mockHost();+ expect(await host.invoke('maker:get-capabilities', ['codex'])).toMatchObject({ supportsSessionAgentSwitch: true });+ expect(await host.invoke('maker:provider:list', [])).toMatchObject({ providers: expect.arrayContaining([expect.objectContaining({ agents: ['codex'] })]) });+ expect(await host.invoke('maker:switch-session-agent', ['session', 'codex', 'next-model'])).toMatchObject({ deferred: true });+ expect(host.state.sessions[0].agentKind).toBe('cc');+ expect(await host.invoke('maker:get-session-agent-switch-intent', ['session'])).toMatchObject({ targetAgentKind: 'codex' });+ await host.invoke('maker:input:enqueue', ['session', { text: 'next message' }]);+ expect(host.state.sessions[0]).toMatchObject({ agentKind: 'codex', model: 'next-model' });+ expect(await host.invoke('maker:get-session-agent-switch-intent', ['session'])).toBeNull();+ expect(host.state.messages.get('session')[0]).toMatchObject({ role: 'user', content: 'next message' });+ });- expect(sessionScreen).toContain('const documentBeforeStop = composerDocumentRef.current;');- expect(sessionScreen).toContain('const latestDraft = await controller.stop();');- expect(sessionScreen).toContain('await sendLatest({ documentOverride: latestDocument });');- expect(sessionScreen.indexOf('const documentBeforeStop = composerDocumentRef.current;')).toBeLessThan(- sessionScreen.indexOf('const latestDraft = await controller.stop();'),- );- expect(sessionScreen).toContain('const latestDocument = latestDraft.trim()');- expect(sessionScreen).toContain('readCurrentDraft: () => draftRef.current');- expect(sessionScreen).toContain('if (selection) input?.rememberSelection(text, selection);');- expect(sessionScreen).toContain('writeVoiceDraft({ draft: text, initialDocument, initialSelection, insertionEnd: selection?.end, replacement });');- expect(sessionScreen).toContain('reconcileComposerVoiceDraft(composerDocumentRef.current, update)');- expect(sessionScreen).toContain('reconcileComposerProjectedText(composerDocumentRef.current, latestDraft)');- expect(sessionScreen).toContain('createMobileVoiceControllerSession({');- expect(sessionScreen).not.toContain('await sendLatest({ draftOverride: latestDraft });');+ it('preserves recovery-key ownership before and after a mock session claims its worktree', async () => {+ const host = mockHost();+ await host.invoke('maker:apply-new-maker-worktree-pref', [{ worktreeEnabled: true }]);+ expect(await host.invoke('maker:get-new-maker-defaults', [])).toEqual({ worktreeEnabled: true });+ expect(await host.invoke('worktree:detect-cwd', [{ cwd: '/repo' }])).toMatchObject({ supportsRecoveryKeyDiscard: true, repoRoot: '/repo' });+ const branches = await host.invoke('worktree:list-branches', [{ baseRepo: '/repo' }]);+ const { name } = await host.invoke('worktree:suggest-name', [{ baseRepo: '/repo' }]);+ const request = { sessionId: 'created', baseRepo: '/repo', name, sourceBranch: branches.branches[1], recoveryKey: 'fixture-recovery-key' };+ const result = await host.invoke('worktree:create', [request]);+ expect(result).toMatchObject({ ok: true, meta: { path: `/repo/.cindy-worktrees/${name}`, branch: `xdt/${name}`, sourceBranch: branches.branches[1] } });+ await expect(host.invoke('worktree:discard-precreated', [{ sessionId: 'created', recoveryKey: 'wrong-key' }])).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });+ expect(await host.invoke('worktree:discard-precreated', [{ sessionId: 'created', recoveryKey: request.recoveryKey }])).toEqual({ discarded: true, branchDeleted: true });+ await host.invoke('worktree:create', [request]);+ await host.invoke('maker:create-session', [{ id: 'created', workingDir: result.meta.path }]);+ expect(host.state.sessions[0]).toMatchObject({ worktreePath: result.meta.path });+ await expect(host.invoke('worktree:discard-precreated', [{ sessionId: 'created', recoveryKey: request.recoveryKey }])).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });});- it('guards the mobile voice composer against the legacy desktop transcription path', () => {- const scopeGuard = readFileSync(resolve(process.cwd(), 'scripts/mobile-scope-guard.mjs'), 'utf8');+ it('rejects retired credential sync with its explicit compatibility error', async () => {+ const host = mockHost();+ await expect(host.invoke('device-link:voice:credential-sync', [])).rejects.toMatchObject({ code: 'VOICE_CREDENTIAL_SYNC_REMOVED' });+ expect(await host.invoke('device-link:voice:dictionary-learning', [])).toMatchObject({ ok: true, ignoreReason: 'mock-host' });+ });- expect(scopeGuard).toContain("roots: ['app']");- expect(scopeGuard).toContain("'transcribeVoice('");- expect(scopeGuard).toContain("'DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL'");- expect(scopeGuard).toContain("'device-link:voice:transcribe'");- expect(scopeGuard).toContain('Mobile voice composer must use the realtime controller + managed Cindy voice service');+ it.each(['safe controller', 'transcribeVoice(', 'DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL', 'device-link:voice:transcribe'])('runs the mobile scope gate against %s', (fixture) => {+ const error = vi.fn();+ const execute = () => runInNewContext(scriptBody('scripts/mobile-scope-guard.mjs', 'const forbiddenFiles ='), {+ mobileRoot: '/mobile', resolve: posix.resolve, join: posix.join, relative: posix.relative, basename: posix.basename,+ existsSync: (path: string) => ['/mobile/app', '/mobile/app/composer.tsx'].includes(path),+ statSync: (path: string) => ({ isFile: () => path.endsWith('.tsx'), isDirectory: () => path === '/mobile/app' }),+ readdirSync: () => ['composer.tsx'], readFileSync: () => fixture,+ console: { log: vi.fn(), error }, process: { exit: (code: number) => { throw new Error(`exit:${code}`); } },+ });+ if (fixture === 'safe controller') { execute(); expect(error).not.toHaveBeenCalled(); }+ else { expect(execute).toThrow('exit:1'); expect(error).toHaveBeenCalledWith(expect.stringContaining('Mobile voice composer must use the realtime controller')); }});});diff --git a/apps/mobile/src/__tests__/navigationLock.test.ts b/apps/mobile/src/__tests__/navigationLock.test.tsindex a16fac45b1..72d32c255c 100644--- a/apps/mobile/src/__tests__/navigationLock.test.ts+++ b/apps/mobile/src/__tests__/navigationLock.test.ts@@ -1,10 +1,24 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';++const navigation = vi.hoisted(() => ({ focused: false, push: vi.fn() }));+vi.mock('react', () => ({+ useCallback: (callback: unknown) => callback,+ useEffect: () => {},+ useMemo: (factory: () => unknown) => factory(),+}));+vi.mock('expo-router', () => ({+ useRouter: () => ({ push: navigation.push }),+ useNavigation: () => ({ isFocused: () => navigation.focused }),+ useFocusEffect: () => {},+}));+import { useGuardedPush } from '../utils/useGuardedPush';import {SAME_TARGET_WINDOW_MS,TRANSITION_WINDOW_MS,createNavigationLock,createRefocusReset,+ forwardNavigationLock,navigationTargetKey,} from '../utils/navigationLock';@@ -134,14 +148,15 @@ describe('useGuardedPush 焦点门(source 契约)', () => {it('push 前必须过 isFocused 门:失焦(导航已在路上)的补点一律丢弃', async () => {// JS 长停摆会把补点分散到多个恢复间隙,墙钟窗口对「跨停摆补点」失效// (2026-07-18 同一会话被连开 N 层实锤);焦点门是时间窗之外的确定性防线。- const { readFileSync } = await import('node:fs');- const { resolve } = await import('node:path');- const source = readFileSync(resolve(process.cwd(), 'src/utils/useGuardedPush.ts'), 'utf8');- const focusGate = source.indexOf('navigation.isFocused() === false');- const lockGate = source.indexOf('forwardNavigationLock.shouldAllow');- const pushCall = source.indexOf('router.push(href)');- expect(focusGate).toBeGreaterThan(-1);- expect(lockGate).toBeGreaterThan(focusGate);- expect(pushCall).toBeGreaterThan(lockGate);+ forwardNavigationLock.reset();+ navigation.push.mockClear();+ navigation.focused = false;+ const push = useGuardedPush();+ push('/sessions/a');+ expect(navigation.push).not.toHaveBeenCalled();+ navigation.focused = true;+ push('/sessions/a');+ expect(navigation.push).toHaveBeenCalledExactlyOnceWith('/sessions/a');+ forwardNavigationLock.reset();});});diff --git a/apps/mobile/src/__tests__/navigationOptionsStability.test.tsx b/apps/mobile/src/__tests__/navigationOptionsStability.test.tsxindex 68b2e81443..0a865ff655 100644--- a/apps/mobile/src/__tests__/navigationOptionsStability.test.tsx+++ b/apps/mobile/src/__tests__/navigationOptionsStability.test.tsx@@ -1,6 +1,7 @@// @vitest-environment jsdomimport { cleanup, render } from '@testing-library/react';-import type { ReactNode } from 'react';+import { useMemo, type ReactNode } from 'react';+import ts from 'typescript';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const seenScreenOptions: unknown[] = [];@@ -59,9 +60,26 @@ describe('navigation option stability', () => {const { resolve } = await import('node:path');const source = await readFile(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8');- expect(source).toContain("const loginStatusBarOptions = useMemo(() => ({");- expect(source).toContain("statusBarStyle: stageTheme === 'dark' ? 'light' : 'dark',");- expect(source).toContain("} as const), [stageTheme]);");- expect(source).toContain('<Stack.Screen options={loginStatusBarOptions} />');+ const tree = ts.createSourceFile('login.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'loginStatusBarOptions') initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!initializer) throw new Error('Missing production login status-bar options');+ const compiled = ts.transpileModule('const options = ' + initializer.getText(tree) + ';', { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const optionsFor = new Function('useMemo', 'stageTheme', compiled + '\nreturn options;');+ function LoginOptions({ stageTheme }: { stageTheme: 'light' | 'dark' }) {+ return <Screen options={optionsFor(useMemo, stageTheme)} />;+ }+ const view = render(<LoginOptions stageTheme="light" />);+ const initial = seenScreenOptions.at(-1);+ expect(initial).toMatchObject({ statusBarStyle: 'dark' });+ view.rerender(<LoginOptions stageTheme="light" />);+ expect(seenScreenOptions.at(-1)).toBe(initial);+ view.rerender(<LoginOptions stageTheme="dark" />);+ expect(seenScreenOptions.at(-1)).not.toBe(initial);+ expect(seenScreenOptions.at(-1)).toMatchObject({ statusBarStyle: 'light' });});});diff --git a/apps/mobile/src/__tests__/navigationTheme.test.ts b/apps/mobile/src/__tests__/navigationTheme.test.tsindex 8d5253dbc2..3d434658ac 100644--- a/apps/mobile/src/__tests__/navigationTheme.test.ts+++ b/apps/mobile/src/__tests__/navigationTheme.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import { createNavigationTheme } from '@/theme/navigationTheme';import { darkColors, lightColors } from '@/theme/tokens';@@ -41,12 +39,4 @@ describe('mobile navigation theme', () => {expect(result.fonts).toBe(baseTheme.fonts);expect(baseTheme.colors.background).toBe('base-background');});-- it('wraps the native stack with the mode-aware navigation theme provider', () => {- const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');-- expect(layout).toContain("mode === 'dark' ? NavigationDarkTheme : NavigationLightTheme");- expect(layout).toContain('<NavigationThemeProvider value={navigationTheme}>');- expect(layout).toContain('contentStyle: { backgroundColor: colors.surface }');- });});diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.tsindex 710dd6a54d..bcebea61b1 100644--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@ -660,7 +660,7 @@ describe('newSessionCreation pipeline', () => {ts.forEachChild(node, findEffect);}findEffect(page);- expect(effect).not.toBe('');+ if (!effect) throw new Error('Missing production creation recovery effect');const restore = vi.fn(() => expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable'));const bindings = {outboxOwner: owner, params: { recoverySessionId: 's1' }, routeDeviceId: scope === 'device' ? 'dev-2' : 'dev-1',diff --git a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.tsindex 67a4b60a9d..f916b6cf95 100644--- a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts+++ b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts@@ -89,7 +89,7 @@ describe('newSessionPreferenceStore', () => {// These are the actual normal/goal creation predicates, not a copied guard.const source = readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');const guards = [...source.matchAll(/const isCurrentOwner = \(\) => \(([\s\S]*?)\n \);/g)];- expect(guards).toHaveLength(2);+ if (guards.length !== 2) throw new Error('Missing production creation guards');for (const [, predicate] of guards) {const accepts = new Function('authOwnerAtCreate', 'accountIdAtCreate', 'isMobileAuthOwnerCurrent', `return (${predicate});`);const currentOwner = getMobileAuthOwner();@@ -100,7 +100,12 @@ describe('newSessionPreferenceStore', () => {}// Existing recovery entries are namespaced by the bare membership ID.expect(getMobileAuthOwner().accountId).toBe('shared-member');- expect(source.match(/const worktreeAccountId = authOwnerAtCreate.accountId;/g)).toHaveLength(2);+ const namespaces = [...source.matchAll(/const worktreeAccountId = ([^;]+);/g)];+ if (namespaces.length !== 2) throw new Error('Missing production recovery namespaces');+ for (const [, expression] of namespaces) {+ const recoveryNamespace = new Function('authOwnerAtCreate', `return (${expression});`);+ expect(recoveryNamespace(getMobileAuthOwner())).toBe('shared-member');+ }});it('stores the last selected device and agent for new sessions', async () => {diff --git a/apps/mobile/src/__tests__/orcaCollab.test.ts b/apps/mobile/src/__tests__/orcaCollab.test.tsindex a4fb7b7b86..4941982740 100644--- a/apps/mobile/src/__tests__/orcaCollab.test.ts+++ b/apps/mobile/src/__tests__/orcaCollab.test.ts@@ -1,5 +1,9 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { act, createElement } from 'react';+import { createRoot } from 'react-dom/client';+import ts from 'typescript';import { beforeAll, describe, expect, it } from 'vitest';import { i18n } from '@/i18n';import {@@ -11,6 +15,14 @@ import {import { excludeOrcaWorkerSessions, selectVisibleDeviceSessions } from '@/session/mobileHome';import { normalizeRemoteMessages } from '@/session/messageNormalize';import type { RemoteMessage, RemoteSession } from '@/session/types';+import { __test_internals as expansion } from '@/session/expandedBlockMemory';+import { buildRemoteSessionSections, summarizeRemoteSessionOverview } from '@/session/sessionList';+import { collaborationRenderer } from './fixtures/messageRendererComponents';++function executeDetail<T>(code: string, globals: Record<string, unknown>): T {+ const emitted = ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ return new Function(...Object.keys(globals), emitted)(...Object.values(globals));+}// orcaCollab 卡片文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦// (全局 mock 默认 en-US)。@@ -295,25 +307,71 @@ describe('selectVisibleDeviceSessions', () => {});it('feeds the derived rows into the device/project list sections', () => {- const detail = readFileSync(resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8');- expect(detail).toContain('selectVisibleDeviceSessions(allSessions, deviceId, projectWorkingDir)');- expect(detail).toContain('buildRemoteSessionSections(sessions,');- expect(detail).toContain('summarizeRemoteSessionOverview(sessions,');+ const detail = ts.createSourceFile('device.tsx', readFileSync(resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const names = new Set(['sessions', 'filterCounts', 'sections']);+ const declarations: string[] = [];+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && names.has(node.name.text) && node.initializer) {+ declarations.push('const ' + node.getText(detail) + ';');+ }+ ts.forEachChild(node, visit);+ }+ visit(detail);+ const allSessions = [+ session({ id: 'lead', orcaRole: 'lead', deviceLinkDeviceId: 'dev-a', workingDir: '/repo/cindy' }),+ session({ id: 'worker', orcaRole: 'worker', deviceLinkDeviceId: 'dev-a', workingDir: '/repo/cindy' }),+ session({ id: 'other-device', orcaRole: null, deviceLinkDeviceId: 'dev-b', workingDir: '/repo/cindy' }),+ session({ id: 'normal', orcaRole: null, deviceLinkDeviceId: 'dev-a', workingDir: '/repo/cindy' }),+ ];+ const result = executeDetail<{ filterCounts: { all: number }; sections: ReturnType<typeof buildRemoteSessionSections> }>(+ declarations.join(String.fromCharCode(10)) + '; return { filterCounts, sections };', {+ useMemo: (compute: () => unknown) => compute(), selectVisibleDeviceSessions,+ buildRemoteSessionSections, summarizeRemoteSessionOverview,+ allSessions, deviceId: 'dev-a', projectWorkingDir: '/repo/cindy',+ messagePreviewIndex: new Map(), pendingInteractionIndex: new Map(), scheduleIndex: new Map(),+ searchQuery: '', statusFilter: 'all', automationScopeKey: null,+ i18nInstance: i18n, t: i18n.t.bind(i18n),+ });+ expect(result.sections.flatMap(section => section.data.map(row => row.session.id)).sort()).toEqual(['lead', 'normal']);+ expect(result.filterCounts.all).toBe(2);});});describe('MessageRenderer wires the orca card', () => {- it('routes message items carrying an orcaCard to OrcaCollabCard', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- expect(source).toContain('item.message.orcaCard');- // F4:透传 screenWidth,使 CollabCardShell layout 随屏宽响应(与 SubagentCard 一致)。- expect(source).toContain('<OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}');- expect(source).toContain('blockKey={JSON.stringify([actions.remoteDeviceId, item.key])}');- expect(source).toContain('controlledExpanded={expanded}');- // Legacy `orca-toggled-` entries meant "collapsed" for dispatch cards; do not read them.- expect(source).toContain('`orca-expanded-${JSON.stringify([accountGeneration, blockKey, card.variant])}`');- expect(source).not.toContain('`orca-toggled-');- expect(source).toContain('onControlledToggle={toggleExpanded}');- expect(source).toContain('testID={`message.orcaCard.${card.variant}`}');+ it('routes real normalized cards and scopes remembered expansions by device and account', () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ const renderer = collaborationRenderer();+ const host = document.createElement('div');+ const root = createRoot(host);+ expansion.reset();+ const [normalized] = normalizeRemoteMessages([message({ id: 'dispatch', role: 'tool_use', content: {+ toolName: 'create_worker', input: { label: 'api', initial_task: 'Build API' },+ } })]);+ const item = { type: 'message', key: 'dispatch', message: normalized };+ const show = (deviceId: string) => createElement(renderer.RenderItemView, { item, actions: { remoteDeviceId: deviceId, screenWidth: 320 } });+ const toggle = () => host.querySelector<HTMLButtonElement>('[data-testid="message.orcaCard.dispatch"]')!;+ try {+ // Legacy dispatch toggles recorded collapsed state and cannot become new expansions.+ expansion.setExpanded('orca-toggled-' + JSON.stringify([1, JSON.stringify(['dev-a', 'dispatch']), 'dispatch']), true);+ act(() => root.render(show('dev-a')));+ expect(toggle().getAttribute('aria-expanded')).toBe('false');+ expect(host.textContent).not.toContain('Build API');+ act(() => toggle().click());+ expect(host.querySelector('[data-testid="message.orcaCardBody"]')?.textContent).toBe('Build API');+ const compact = toggle().getAttribute('data-style');+ act(() => root.render(createElement(renderer.RenderItemView, { item, actions: { remoteDeviceId: 'dev-a', screenWidth: 800 } })));+ expect(toggle().getAttribute('data-style')).not.toBe(compact);+ act(() => root.render(null));+ act(() => root.render(show('dev-a')));+ expect(toggle().getAttribute('aria-expanded')).toBe('true');+ act(() => root.render(show('dev-b')));+ expect(toggle().getAttribute('aria-expanded')).toBe('false');+ renderer.state.accountGeneration = 2;+ act(() => root.render(show('dev-a')));+ expect(toggle().getAttribute('aria-expanded')).toBe('false');+ } finally {+ act(() => root.unmount());+ expansion.reset();+ }});});diff --git a/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts b/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.tsindex f2bab2dac1..fc9dac65d1 100644--- a/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts+++ b/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';import { afterEach, describe, expect, it } from 'vitest';import {clearAllPendingInteractionCollapse,@@ -96,9 +97,22 @@ describe('pendingInteractionCollapseStore', () => {const sessionScreenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');// 页面组件不得再自持收起态:它会随「离开任务」卸载一起丢(#1493 review)。- expect(sessionScreenSource).toContain('useCollapsedPendingRequestIds(sessionId)');- expect(sessionScreenSource).toContain('prunePendingInteractionCollapse(sessionId, pending, {');- expect(sessionScreenSource).not.toContain('setCollapsedPendingRequestIds');- expect(sessionScreenSource).not.toContain('useState<readonly string[]>([])');+ const tree = ts.createSourceFile('session.tsx', sessionScreenSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let read: ts.Expression | undefined, prune: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'collapsedPendingRequestIds') read = node.initializer;+ if (ts.isCallExpression(node) && node.expression.getText(tree) === 'prunePendingInteractionCollapse') prune = node;+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!read || !prune) throw new Error('Missing production collapse store consumers');+ const readPage = new Function('useCollapsedPendingRequestIds', 'sessionId', `return (${read.getText(tree)});`);+ const prunePage = new Function('prunePendingInteractionCollapse', 'sessionId', 'pending', 'pendingInteractionsAuthoritative', `${prune.getText(tree)};`);+ togglePendingInteractionCollapse('session-1', 'ask-1');+ expect(readPage(getCollapsedPendingRequestIds, 'session-1')).toEqual(['ask-1']);+ prunePage(prunePendingInteractionCollapse, 'session-1', [], false);+ expect(readPage(getCollapsedPendingRequestIds, 'session-1')).toEqual(['ask-1']);+ prunePage(prunePendingInteractionCollapse, 'session-1', [], true);+ expect(readPage(getCollapsedPendingRequestIds, 'session-1')).toEqual([]);});});diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsindex d59f71c0e8..64c0d5de37 100644--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -1,3 +1,6 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';/*** 待发送气泡 → 消息流渲染项的构造。*@@ -420,60 +423,36 @@ describe('pending_send 渲染接线', () => {expect(isPendingSendItemSelected(item, expanded.pendingSendSelectedClientId)).toBe(true);});- it('keeps pendingSend on the renderer actions object', async () => {- // 回归防线:MessageRenderer 的 actions 是显式组装的 useMemo。漏掉这一项时 props 和- // 类型都还对(interface 上有、JSX 也传了),但 actions.pendingSend 是 undefined,渲染- // 分支直接 null —— 气泡整个不画,乐观显示凭空消失(实测踩过)。- const { readFileSync } = await import('node:fs');- const { resolve: resolvePath } = await import('node:path');- const source = readFileSync(- resolvePath(process.cwd(), 'src/session/MessageRenderer.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const actionsStart = source.indexOf('const actions: MessageActions');- const actionsEnd = source.indexOf('viewportLayout.contentWidth,\n ]);', actionsStart);- const actionsBlock = source.slice(actionsStart, actionsEnd);- expect(actionsBlock).toContain('pendingSend,');- expect(source).toContain('buildMobileMessageListExtraData(');- expect(source).toContain('extraData={messageListExtraData}');- // 渲染分支存在,且 items 的联合类型里有这一支。- expect(source).toContain("case 'pending_send':");- expect(source).toContain('actions={actions.pendingSend}');- const bubbleSource = readFileSync(- resolvePath(process.cwd(), 'src/session/PendingSendBubble.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- expect(bubbleSource).toContain('<SentInlineAtomBody');- expect(bubbleSource).toContain('interactiveAtoms={false}');- expect(bubbleSource).toContain('maxVisibleLines={collapsedLines}');- expect(bubbleSource).toContain('LONG_USER_MESSAGE_COLLAPSED_LINES');- // 状态徽标保留独立入口和定位,气泡正文通过 touch end 展开队列操作;移动手势不触发菜单。- const badgeStart = bubbleSource.indexOf('<Pressable\n accessibilityHint={item.hint');- const badgeEnd = bubbleSource.indexOf('\n </Pressable>', badgeStart);- expect(badgeStart).toBeGreaterThan(-1);- const badge = bubbleSource.slice(badgeStart, badgeEnd);- expect(badge).toContain('testID={`pendingSend.badge.${item.phase}`}');- expect(badge).toContain('actions.onSelect(selected ? null : item.clientId)');- expect(badge).not.toContain('renderText(');- expect(badge).toContain('badgePosition');- expect(bubbleSource).toContain('event.nativeEvent.layout.x - 28 - spacing.sm');- expect(bubbleSource).toContain('onLayout={hasAttachments ? undefined : measureBadgeAnchor}');- expect(bubbleSource.indexOf('testID={`pendingSend.bubble.${item.clientId}`}')).toBeGreaterThan(badgeEnd);- expect(bubbleSource).toContain('onTouchEnd={interactive ? handleBubbleTouchEnd : undefined}');- expect(bubbleSource).toContain('const collapseLatched = collapseLatchBody === displayBody;');- expect(bubbleSource).toContain('if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBody);');- expect(bubbleSource).toContain('(measureBody && collapseLatched) || collapseResolved');- const actionPillStart = bubbleSource.indexOf(' actionPill: {');- const actionPillEnd = bubbleSource.indexOf('\n },', actionPillStart);- const actionPillStyle = bubbleSource.slice(actionPillStart, actionPillEnd);- expect(actionPillStart).toBeGreaterThan(-1);- expect(actionPillStyle).toContain('minHeight: 44');- // 粘贴时已上传到媒体总仓的图(cindy-media://blobs/…)本地没有文件,气泡要靠远端取件- // 才有缩略图 —— 漏传 resolver 就只能画空占位格。- expect(source).toContain('resolveRemoteMedia={actions.onResolveRemoteMedia}');- });+});+ it('preserves pending send actions through the production renderer memo', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const tree = ts.createSourceFile('renderer.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let callback: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'actions' && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!callback) throw new Error('Missing renderer actions memo');+ const identifiers = new Set<string>();+ function readNames(node: ts.Node) {+ if (ts.isShorthandPropertyAssignment(node)) identifiers.add(node.name.text);+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.initializer)) identifiers.add(node.initializer.text);+ ts.forEachChild(node, readNames);+ }+ readNames(callback);+ const pendingSend = { onSelect: vi.fn(), onRemove: vi.fn(), onSendNow: vi.fn() };+ const bindings: Record<string, unknown> = Object.fromEntries([...identifiers].map((name) => [name, undefined]));+ Object.assign(bindings, { pendingSend, viewportLayout: { contentWidth: 390 } });+ const compiled = ts.transpileModule('const project = ' + callback.getText(tree) + ';', { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const actions = new Function(...Object.keys(bindings), compiled + '\nreturn project();')(...Object.values(bindings));+ expect(actions.pendingSend).toBe(pendingSend);+ actions.pendingSend.onSelect('queued');+ expect(pendingSend.onSelect).toHaveBeenCalledWith('queued');+ });+describe('pendingSendSpins', () => {it('spins only while the message has not been confirmed as queued', () => {expect(pendingSendSpins('sending')).toBe(true);diff --git a/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts b/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.tsindex 9b5c5b14fb..262f29e4ba 100644--- a/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts+++ b/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts@@ -1,3 +1,4 @@+// guard: credentials-and-local-storage.md: root-owned recovery callbacks must fence both account identity and generation; otherwise stale callbacks mutate another account recovery ledger.import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';diff --git a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts b/apps/mobile/src/__tests__/pushNotificationsRealm.test.tsindex 370f087fbb..98e4779f11 100644--- a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts+++ b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const store = vi.hoisted(() => new Map<string, string>());@@ -104,21 +102,6 @@ describe('push notification realm routing', () => {vi.unstubAllGlobals();});- it('re-registers the restored owner after an account-switch rollback', () => {- const source = readFileSync(- resolve(process.cwd(), 'src/notifications/PushNotificationsBridge.tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');- const registrationStart = source.indexOf('// 登录态就绪后同步注册状态');- const registrationBody = source.slice(- registrationStart,- source.indexOf('// APNs token 轮换', registrationStart),- );-- expect(registrationBody).toContain('auth.accountGeneration');- expect(registrationBody).toContain('syncPushRegistration(');- });-it('向当前会话区域注册,但推送构建线仍保持安装包区域', async () => {envState.activeRealm = 'global';const apiFetch = vi.fn().mockResolvedValue({ registered: true });diff --git a/apps/mobile/src/__tests__/recentMessageHistories.test.tsx b/apps/mobile/src/__tests__/recentMessageHistories.test.tsxindex 314294ac1d..d26c29aa4d 100644--- a/apps/mobile/src/__tests__/recentMessageHistories.test.tsx+++ b/apps/mobile/src/__tests__/recentMessageHistories.test.tsx@@ -1,6 +1,4 @@// @vitest-environment jsdom-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { act, createContext, useEffect, useImperativeHandle, useRef, useState, type ReactNode, type Ref } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -233,26 +231,7 @@ describe('resident five-task message lists outside route lifetimes', () => {expect(residentHost.compareDocumentPosition(drawer) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0);expect(drawer.closest('[data-layout]')?.getAttribute('data-layout')).toContain('"zIndex":40');});- it('does not keep the old route preloading mechanism alongside the resident host', () => {- const home = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');- expect(home).not.toContain('useRecentTaskPreload');- expect(home).not.toContain('router.prefetch');- const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');- // Source structure is independent of checkout line endings.- for (const source of [layout.replace(/\r\n/g, '\n'), layout.replace(/\r?\n/g, '\r\n')]) {- const provider = source.search(/<RecentMessageHistoriesProvider(?:\s|>)/);- const residentProvider = source.indexOf('<ResidentHomeListProvider>');- const stack = source.search(/<Stack\s/);- expect(provider).toBeGreaterThanOrEqual(0);- expect(residentProvider).toBeGreaterThan(provider);- expect(stack).toBeGreaterThan(provider);- expect(stack).toBeGreaterThan(residentProvider);- expect(source.indexOf('</ResidentHomeListProvider>')).toBeGreaterThan(stack);- expect(source.indexOf('</RecentMessageHistoriesProvider>')).toBeGreaterThan(- source.indexOf('</ResidentHomeListProvider>'),- );- }- });+it('clears all instances at an account boundary', async () => {await show('a'); await show('b');await act(async () => setMobileAuthOwner('two'));diff --git a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts b/apps/mobile/src/__tests__/remoteListIncludePinned.test.tsindex d859d31faf..cfa4803ed5 100644--- a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts+++ b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts@@ -1,3 +1,4 @@+// guard: protocol-compatibility.md: list bootstrap flags and schedule-index invalidation must agree across Home, device detail and event adapters; static wire/call-site contract.import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';diff --git a/apps/mobile/src/__tests__/remoteSyncTask.test.ts b/apps/mobile/src/__tests__/remoteSyncTask.test.tsindex a9517bff0c..f93eed3ee0 100644--- a/apps/mobile/src/__tests__/remoteSyncTask.test.ts+++ b/apps/mobile/src/__tests__/remoteSyncTask.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';import {createRemoteSyncCoordinator,@@ -19,10 +17,6 @@ function nextTick(): Promise<void> {return new Promise((resolve) => setTimeout(resolve, 0));}-function readSessionScreenSource(): string {- return readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');-}-describe('remote sync task runner', () => {it('shares one successful peer reopen across staggered retries in the same sync run', async () => {const reopen = vi.fn(async () => undefined);@@ -206,48 +200,4 @@ describe('remote sync coordinator', () => {await expect(task).rejects.toThrow('first failed');expect(runs).toEqual([['first'], ['follow-up']]);});-- it('clears loading when a queued sync is blocked for a newly-created session', () => {- const source = readSessionScreenSource();- expect(source).toContain(- 'if (shouldBlockSessionSync(sessionId)) {\n if (!syncRun.isStale()) setLoading(false);\n return;\n }',- );- });-- it('resets loading when the reused screen switches sessions', () => {- const source = readSessionScreenSource();- expect(source).toContain(- 'setRewindState({ kind: \'idle\' });\n setMessageActionBusy(null);\n setLoading(false);',- );- });-- it('uses the force-reopen callback for subscription and snapshot retries', () => {- const source = readSessionScreenSource();- expect(source).toContain(- 'reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion)',- );- expect(source).toContain(- 'await syncReopenCoordinator.reopenAfter(failedAtVersion);',- );- expect(source).toContain(- 'const syncReopenCoordinator = createRemoteSyncReopenCoordinator(',- );- expect(source).not.toContain(- 'reopenLink: async () => {\n await openLink(deviceId);\n }',- );- });-- it('applies coordinator context and task changes after render commits', () => {- const source = readFileSync(- resolve(process.cwd(), 'src/device-link/remoteSyncTask.ts'),- 'utf8',- ).replace(/\r\n/g, '\n');- expect(source).toContain(- 'useLayoutEffect(() => {\n taskRef.current = task;\n coordinatorRef.current?.setContext(contextKey);\n }, [contextKey, task]);',- );- expect(source).not.toContain(- ' taskRef.current = task;\n const coordinatorRef =',- );- expect(source).not.toContain('coordinatorRef.current.setContext(contextKey);');- });});diff --git a/apps/mobile/src/__tests__/revokedAccessTipDismissal.test.ts b/apps/mobile/src/__tests__/revokedAccessTipDismissal.test.tsindex bab03a27ce..90d9a7ecd2 100644--- a/apps/mobile/src/__tests__/revokedAccessTipDismissal.test.ts+++ b/apps/mobile/src/__tests__/revokedAccessTipDismissal.test.ts@@ -1,3 +1,4 @@+// guard: DESIGN.md Dialog & Modal closing affordance: backdrop, explicit close and system Back must use the same closing contract.import { readFileSync } from "node:fs";import { resolve } from "node:path";import { describe, expect, it } from "vitest";diff --git a/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts b/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.tsindex 9cfd9e69f1..c61f221ae9 100644--- a/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts+++ b/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';import { afterEach, describe, expect, it, vi } from 'vitest';import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';@@ -100,11 +101,25 @@ describe('task page schedule index gate', () => {expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);});- it('gates the task page read-marking scan before it starts', () => {+ it('gates the task page read-marking scan before it starts', async () => {const page = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');- const effect = page.slice(page.indexOf('const cancel = deferScheduleIndexHydration(() => {'));- expect(effect.indexOf('if (!sessionMayHaveScheduleRuns(deviceId, sessionId, sessionSourceForSchedule)) return;'))- .toBeLessThan(effect.indexOf('markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive'));- expect(page).toContain('scheduleNoticeSource, sessionId, sessionSourceForSchedule]));');+ const tree = ts.createSourceFile('session.tsx', page, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let effect: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isCallExpression(node) && node.expression.getText(tree) === 'deferScheduleIndexHydration') effect = node.arguments[0];+ ts.forEachChild(node, visit);+ }+ visit(tree);+ if (!effect) throw new Error('Missing production schedule hydration callback');+ const markSessionScheduleRunsRead = vi.fn(async () => undefined);+ const f = maker();+ await loadSharedSessionScheduleIndex('mac', f.maker);+ for (const sessionId of ['ordinary', 'pr-task']) {+ const bindings = { sessionMayHaveScheduleRuns, deviceId: 'mac', sessionId, sessionSourceForSchedule: undefined,+ withTransientRemoteRetry: async (operation: () => unknown) => operation(), markSessionScheduleRunsRead, maker: f.maker,+ isActive: () => true, setScheduleFailure: vi.fn(), scheduleNoticeSource: 'test' };+ new Function(...Object.keys(bindings), `return (${effect.getText(tree)})();`)(...Object.values(bindings));+ expect(markSessionScheduleRunsRead).toHaveBeenCalledTimes(sessionId === 'ordinary' ? 0 : 1);+ }});});diff --git a/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts b/apps/mobile/src/__tests__/scheduleNoticeWiring.test.tsindex 71d885d1bc..3e1a503a4d 100644--- a/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts+++ b/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts@@ -1,23 +1,89 @@+// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { act, createElement, useCallback, useEffect, type EffectCallback } from 'react';+import { createRoot, type Root } from 'react-dom/client';import ts from 'typescript';-import { expect, it } from 'vitest';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { projectScheduleEvent } from '@cindy/maker-shared/schedule-events';-it('refreshes the actual notice effect when a completed run is later bound to the task', () => {- const source = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);- let dependencies: string[] = [];- function visit(node: ts.Node) {- if (ts.isCallExpression(node) && node.expression.getText(source) === 'useCallback'- && node.arguments[0]?.getText(source).includes('setScheduleFailure') && node.arguments[1] && ts.isArrayLiteralExpression(node.arguments[1])) {- dependencies = node.arguments[1].elements.map((element) => element.getText(source));- }- ts.forEachChild(node, visit);- }- visit(source);- const event = projectScheduleEvent({ type: 'session-bound', scheduleId: 'schedule', runId: 'run', sessionId: 'task' });- expect(event.refresh.sessionIndex).toBe(true);- expect(event.refresh.unreadSummary).toBe(false);- expect(dependencies).toContain('scheduleEventSnapshot.sessionIndexVersion');- expect(dependencies).toContain('remoteHistoryAvailable');- expect(dependencies).toContain('appStateActive');+import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';+import { withTransientRemoteRetry } from '@/device-link/remoteRetry';+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';+import { loadSharedSessionScheduleIndex, resetScheduleIndexThrottleForTesting, sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';+import { markSessionScheduleRunsRead } from '@/session/scheduleRunRead';++// Keep the historical session-bound/visibility regression, but execute the+// production focus-effect expression and real mark-read orchestration instead+// of asserting its dependency strings. Deferred idle work is run synchronously.+const screen = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let expression: string | undefined;+function visit(node: ts.Node) {+ if (ts.isCallExpression(node) && node.expression.getText(screen) === 'useFocusEffect'+ && node.getText(screen).includes('setScheduleFailure')) expression = node.getText(screen);+ ts.forEachChild(node, visit);+}+visit(screen);+if (!expression) throw new Error('Schedule notice focus effect was not found');+const emitted = ts.transpileModule(expression, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+function useFocusEffect(effect: EffectCallback) { useEffect(effect, [effect]); }+let root: Root;+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ resetScheduleIndexThrottleForTesting();+ remoteScheduleEventStore.clearDevice('notice-device');+ root = createRoot(document.createElement('div'));+});+afterEach(() => {+ act(() => root.unmount());+ resetScheduleIndexThrottleForTesting();+ remoteScheduleEventStore.clearDevice('notice-device');});++it.each(['binding-event', 'history-ready', 'app-active'] as const)(+ 'reads a later-bound run and updates its failure notice when %s changes', async trigger => {+ let runs: Record<string, unknown>[] = [];+ const markRunRead = vi.fn(async () => undefined);+ const maker = { schedule: {+ list: async () => [{ id: 'schedule', name: 'Report', status: 'active' }],+ listRuns: async () => runs,+ markRunRead,+ } } as unknown as MobileMakerTransport;+ await loadSharedSessionScheduleIndex('notice-device', maker);+ const setScheduleFailure = vi.fn();+ const stable = { useCallback, useFocusEffect, maker, withTransientRemoteRetry,+ sessionMayHaveScheduleRuns, markSessionScheduleRunsRead, setScheduleFailure,+ deviceId: 'notice-device', sessionId: 'task', connectionEpoch: 1, invoke: vi.fn(),+ sessionSourceForSchedule: 'desktop', scheduleNoticeSource: 'owner/notice-device/task',+ messageScreenFocusedRef: { current: true }, messageAppActiveRef: { current: true },+ deferScheduleIndexHydration: (callback: () => void) => { callback(); return vi.fn(); },+ };+ const execute = new Function(...Object.keys(stable), 'appStateActive', 'remoteHistoryAvailable', 'scheduleEventSnapshot', emitted);+ type Gates = { appStateActive: boolean; remoteHistoryAvailable: boolean; version: number };+ function Notice({ appStateActive, remoteHistoryAvailable, version }: Gates) {+ execute(...Object.values(stable), appStateActive, remoteHistoryAvailable, { sessionIndexVersion: version });+ return null;+ }+ const gates = { appStateActive: trigger !== 'app-active', remoteHistoryAvailable: trigger !== 'history-ready', version: remoteScheduleEventStore.getSnapshot('notice-device').sessionIndexVersion };+ await act(async () => root.render(createElement(Notice, gates)));+ expect(markRunRead).not.toHaveBeenCalled();+ expect(setScheduleFailure).not.toHaveBeenCalled();++ runs = [{ id: 'run', scheduleId: 'schedule', sessionId: 'task', status: 'failed', firedAt: 1 }];+ const event = { type: 'session-bound' as const, scheduleId: 'schedule', runId: 'run', sessionId: 'task' };+ const projection = projectScheduleEvent(event);+ expect(projection.refresh.sessionIndex).toBe(true);+ expect(projection.refresh.unreadSummary).toBe(false);+ remoteScheduleEventStore.apply('notice-device', event);+ gates.version = remoteScheduleEventStore.getSnapshot('notice-device').sessionIndexVersion;+ await act(async () => root.render(createElement(Notice, { ...gates })));+ if (trigger !== 'binding-event') {+ expect(markRunRead).not.toHaveBeenCalled();+ expect(setScheduleFailure).not.toHaveBeenCalled();+ gates.appStateActive = true;+ gates.remoteHistoryAvailable = true;+ await act(async () => root.render(createElement(Notice, { ...gates })));+ }+ expect(markRunRead).toHaveBeenCalledExactlyOnceWith('run');+ expect(setScheduleFailure).toHaveBeenCalledExactlyOnceWith({ source: 'owner/notice-device/task', run: { runId: 'run', scheduleId: 'schedule', firedAt: 1, failureKind: 'execution' } });+ },+);diff --git a/apps/mobile/src/__tests__/scrollWindowModel.test.ts b/apps/mobile/src/__tests__/scrollWindowModel.test.tsindex 399fb1373a..f88145019c 100644--- a/apps/mobile/src/__tests__/scrollWindowModel.test.ts+++ b/apps/mobile/src/__tests__/scrollWindowModel.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import {evaluateMessageWindowUpdate,@@ -97,20 +95,7 @@ describe('scrollWindowModel', () => {});});- it.each(['\n', '\r\n'])('restores the load-earlier affordance after unchanged reopen with %j line endings', (lineEnding) => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r?\n/g, lineEnding);- // 重开"无新内容"分支(metaChanged=false)也补设 hasOlderMessages,用服务端总数 vs in-store 推断。- expect(source).toMatch(/hasOlderMessagesAfterReopen\(\s*sessionMeta\._count\?\.messages, remoteSessionStore\.getMessages\(sessionId\),?\s*\)/);- // 仍保留有新内容时的精确(page-based)判定。这个值现在同时喂给 store 的窗口连续性判据- // (moreBeyondWindow,见 #1222):两者本就该同源 —— 「本页上沿之外还有历史」既决定是否点亮- // 「加载更早」,也决定能不能信任早于本页的缓存段。- expect(source).toContain('const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);');- expect(source).toContain('setHasOlderMessages(moreBeyondWindow);');- expect(source).toMatch(/if \(history === null\) \{\s*messageWindowReconciledRef\.current = true;\s*setHasOlderMessages\(hasOlderMessagesAfterReopen\(/);- expect(source).toMatch(- /setLatestMessageWindow\(sessionId, historyPage, \{\s*authority: messageAuthority,\s*moreBeyondWindow,\s*\}\)/,- );- });+});describe('history browse intent', () => {diff --git a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts b/apps/mobile/src/__tests__/sendEnqueueRetry.test.tsindex 1c7fa5de25..a1a0f20a3f 100644--- a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts+++ b/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts@@ -1,3 +1,4 @@+// guard: protocol-compatibility.md: a lost in-flight acknowledgement is not proof of non-delivery; both enqueue adapters must preserve the no-duplicate retry boundary.import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';diff --git a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts b/apps/mobile/src/__tests__/sentMessageAtoms.test.tsindex ecc7fb6bc0..d48ef3330e 100644--- a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts+++ b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts@@ -1,6 +1,60 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import * as React from 'react';+import ts from 'typescript';+import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';+import { InlineQuoteChip } from '@/session/InlineQuoteChip';+import { InlineReferenceChip } from '@/session/InlineReferenceChip';++vi.mock('react-native', () => ({ View: 'View', StyleSheet: { create: (styles: unknown) => styles } }));+vi.mock('@/components/AppText', () => ({ Text: 'Text' }));+vi.mock('lucide-react-native', () => ({ FileText: 'FileText' }));+vi.mock('@/session/InlineQuoteChip', () => ({ InlineQuoteChip: 'QuoteChip' }));+vi.mock('@/session/InlineReferenceChip', () => ({ InlineReferenceChip: 'ReferenceChip' }));+vi.mock('@/theme', () => ({+ useTheme: () => ({ colors: { textSecondary: '#333' } }), useThemedStyles: () => ({}),+ lineHeight: { bodyLarge: 20 }, spacing: { xs: 4 }, iconSize: { sm: 16 }, iconStroke: { regular: 2 },+}));++describe('production sent atom body', () => {+ it('routes text through its caller renderer and keeps atom payloads behind their chips', () => {+ const renderText = vi.fn((text: string) => React.createElement('markdown', null, text));+ const open = vi.fn();+ const tree = SentInlineAtomBody({ tokens: [+ { kind: 'text', text: '**bold**' }, { kind: 'quote', quote: { text: 'Quote' } },+ { kind: 'pasted', text: 'Private payload', display: 'Pasted text' }, { kind: 'slash', text: '/help' },+ ], renderText, onOpenPayload: open });+ const children = tree.props.children as React.ReactElement<any>[];+ expect(renderText).toHaveBeenCalledWith('**bold**', 0);+ expect(children[0].type).toBe('markdown');+ expect(children[1].type).toBe(InlineQuoteChip);+ expect(children[2].type).toBe(InlineReferenceChip);+ expect(children[2].props.label).toBe('Pasted text');+ children[2].props.onPress();+ expect(open).toHaveBeenCalledWith({ kind: 'text', title: 'Pasted text', body: 'Private payload' });+ expect(children[3].props.label).toBe('/help');+ });++ it('clamps structured long content as a whole without allowing hidden payload interaction', () => {+ const tree = SentInlineAtomBody({ tokens: [{ kind: 'pasted', text: 'Hidden payload', display: 'Pasted text' }],+ interactiveAtoms: false, maxVisibleLines: 3, onOpenPayload: vi.fn() });+ expect(tree.props.style).toContainEqual({ maxHeight: 68, overflow: 'hidden' });+ expect(tree.props.children[0].props.onPress).toBeUndefined();+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const ast = ts.createSourceFile('renderer.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let initializer: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'collapseMeasureEnabled') initializer = node.initializer;+ ts.forEachChild(node, visit);+ }+ visit(ast);+ if (!initializer) throw new Error('Missing production long-message measurement gate');+ const measure = new Function('isUser', 'hookSource', 'item', 'displayBubbleBody', 'collapseThreshold', 'mayExceedVisualLineThreshold', 'rendersSentInlineBody', 'return (' + initializer.getText(ast) + ');');+ expect(measure(true, undefined, { message: { kind: 'user' } }, 'Pasted text\n'.repeat(20), 3, () => true, true)).toBe(true);+ expect(measure(true, undefined, { message: { kind: 'user', systemCardType: 'notice' } }, 'Pasted text\n'.repeat(20), 3, () => true, true)).toBe(false);+ });+});import { formatQuoteForSend, parseChatQuoteSegments } from '@cindy/maker-shared/chat-quotes';import {buildSentInlineTokens,@@ -9,35 +63,6 @@ import {} from '@/session/sentMessageAtoms';describe('sent message atoms', () => {- it('keeps atom chips while rendering ordinary chunks with full Markdown semantics', () => {- const atomSource = readFileSync(resolve(process.cwd(), 'src/session/SentInlineAtomBody.tsx'), 'utf8');- const rendererSource = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');-- expect(atomSource).toContain('<InlineQuoteChip');- expect(atomSource).toContain('<InlineReferenceChip');- expect(atomSource).toContain('renderText(token.text, index)');- expect(atomSource).toContain('selectable={selectable}');- expect(rendererSource).toContain('<MarkdownBody');- expect(rendererSource).toContain('text={text}');- expect(atomSource).not.toContain('splitAnchoredSessionMessageLinks');- expect(atomSource).not.toContain('<SentMessageAnchorChip');- expect(atomSource).not.toContain('parseMobileMarkdownInlines(part.text)');- });-- it('keeps atomized long messages structured while collapsed', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const collapseStart = source.indexOf('const collapseMeasureEnabled =');- const collapseEnd = source.indexOf(';', collapseStart);-- expect(collapseStart).toBeGreaterThan(-1);- expect(collapseEnd).toBeGreaterThan(collapseStart);- expect(source.slice(collapseStart, collapseEnd)).not.toContain('!rendersSentInlineBody');- expect(source).toContain('maxVisibleLines={collapsedLineCount}');- expect(source).toContain('testID="message.collapsedSentInlineAtoms"');- expect(source).toContain('selectable={canSelectVisibleText}');- expect(source).toContain('interactiveAtoms={false}');- });-it('splits exact pasted-text and slash ranges without guessing', () => {const text = '/compact before first\nsecond after';expect(buildSentInlineTokens(diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.tsindex 61adc4418a..ab986a0308 100644--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts@@ -261,3 +261,48 @@ describe('session Agent switch UI wiring', () => {expect(controlAction).toContain('setError(formatRemoteError(err));');});});++// guard: Permission ownership: bot-owned session controls remain host-only while user send/stop remain usable.+describe("hostManagedSession.test.ts call-site contracts", () => {+it('hides host-owned settings while preserving permission controls and the composer', () => {+ const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');+ expect(source).toContain('const sessionManagedByHost = useHostManagedSession(');+ expect(source).toContain('messageOnly={sessionManagedByHost}');+ const details = readFileSync(resolve(process.cwd(), 'src/session/SessionMenuSheet.tsx'), 'utf8');+ expect(details).toContain('visible && !messageOnly');+ expect(details).toContain('const mainActions = messageOnly ? []');+ expect(details).toContain('const deleteAction = messageOnly ? undefined');+ expect(details).toContain("!messageOnly && view === 'info'");+ expect(source).toContain('{renderSessionPermissionButton()}');+ expect(source).toContain('currentSession && runtimeOptions ? (');+ expect(source).not.toContain('!sessionManagedByHost ? renderSessionPermissionButton() : null');+ expect(source).toContain('{!sessionManagedByHost && composerRuntimeSummary ? (');+ const modelAccess = source.slice(source.indexOf('const canConfigureSessionModel'), source.indexOf('// 共享模型自造'));+ expect(modelAccess).toContain('canUseRemoteSessionControls');+ expect(modelAccess).toContain('!sessionManagedByHost');+ expect(modelAccess).toContain('!isSharedTaskPeer(deviceId)');+ const modelPicker = source.slice(source.indexOf('const toggleComposerModelPicker'), source.indexOf('// 账号限额按需拉取'));+ expect(modelPicker).toContain('if (!canConfigureSessionModel)');+ expect(modelPicker).toContain('setModelSheetOpen(false);');+ expect(source).toContain('{renderComposerAttachmentButton()}');+ expect(source).toContain('{renderComposerInlineStop()}');+ });+});++// guard: protocol-compatibility.md: never advertise a confirmation handshake the mobile controller cannot honor.+it('does not advertise unimplemented model-window confirmations across context and transport', () => {+const contextSource = readFileSync(+ resolve(process.cwd(), "src/device-link/DeviceLinkContext.tsx"),+ "utf8",+ );+const transportSource = readFileSync(+ resolve(process.cwd(), "src/device-link/mobileMakerTransport.ts"),+ "utf8",+ );+expect(contextSource).not.toContain(+ "CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1",+ );+expect(contextSource).not.toContain("model-window-confirmation-v1");+expect(transportSource).not.toContain("confirmedOverflow");+expect(transportSource).not.toContain("confirmedContextWindow");+});diff --git a/apps/mobile/src/__tests__/sessionBottomViewport.test.ts b/apps/mobile/src/__tests__/sessionBottomViewport.test.tsindex 92a8156fac..f4695a1e87 100644--- a/apps/mobile/src/__tests__/sessionBottomViewport.test.ts+++ b/apps/mobile/src/__tests__/sessionBottomViewport.test.ts@@ -30,9 +30,6 @@ function style(node: ts.JsxElement, bindings: Record<string, unknown>) {it('clips the input and held card at the selected region while measuring only the bottom content', () => {const viewport = element('session.bottomViewport');const layer = element('session.bottomLayer');- expect(layer.parent).toBe(viewport);- expect(layer.openingElement.getText(source)).toContain('ref={bottomOverlayRef}');- expect(viewport.openingElement.getText(source)).toContain('pointerEvents="box-none"');const regions: ReservedRegion[][] = [[{ kind: 'division', x: 0, y: 380, width: 800, height: 20 }],[{ kind: 'division', x: 390, y: 0, width: 20, height: 800 }],@@ -56,9 +53,6 @@ it('clips the input and held card at the selected region while measuring only thexpect(input.overflow).toBe('visible');expect(input.maxHeight).toBe(region.height);expect(input.bottom).toBe(-geometry.insets.bottom);- expect(viewport.getText(source)).toContain('<SessionComposerPalette');- expect(viewport.getText(source)).toContain('<ComposerActivityStatus');- expect(viewport.getText(source)).toContain('<SessionComposerInput');}});@@ -72,7 +66,7 @@ it('keeps the newest row above the measured phone composer, including expanded its.forEachChild(node, visit);}visit(source);- expect(inset).toBeDefined();+ if (!inset) throw new Error('Missing production content bottom inset');// Execute the actual SessionScreen prop and MessageRenderer padding helper.const contentInset = new Function('bottomOverlayHeight', `const companionInlineInteraction = false, shareSelectionActive = false,diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.tsindex cc8557e402..65960001e0 100644--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts@@ -1,186 +1,145 @@-import { readFileSync } from 'node:fs';+import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--describe('mobile session main layer desktop-first noise budget', () => {- it('keeps the empty message state as a short desktop-style status', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const emptyStart = source.indexOf('function EmptyMessages');- const emptyEnd = source.indexOf('function MessageListActionButton', emptyStart);- const emptySource = source.slice(emptyStart, emptyEnd);-- expect(emptySource).toContain('message.renderer.emptyMessages');- expect(emptySource).not.toContain('这台电脑暂无活动消息');- expect(emptySource).not.toContain('先在桌面端创建或继续一个任务');- expect(emptySource).not.toContain('emptyText');- });-- it('shows a syncing placeholder instead of a blank message area during the first sync', () => {- const rendererSource = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const routeSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- // 首同步期消息区立即渲染 SyncingMessages(spinner + 「正在同步」),- // 而不是干净空白——手机消息要走 device-link 往返桌面,空白会被读成"卡住了"。- const syncingStart = rendererSource.indexOf('function SyncingMessages');- expect(syncingStart).toBeGreaterThan(-1);- const syncingEnd = rendererSource.indexOf('function MessageListActionButton', syncingStart);- const syncingSource = rendererSource.slice(syncingStart, syncingEnd);- expect(syncingSource).toContain('message.renderer.syncing');- expect(syncingSource).toContain('ActivityIndicator');- expect(syncingSource).not.toContain('setTimeout');- expect(rendererSource).toContain('ListEmptyComponent={syncingWhileEmpty');- expect(rendererSource).toContain('<SyncingMessages />');- // Also syncing while a window of only hidden rows pages back (hiddenHistoryChase).- expect(routeSource).toContain('syncingWhileEmpty={syncingWhileEmpty || chasingHiddenHistory}');+import ts from 'typescript';+import * as React from 'react';+import { describe, expect, it, vi } from 'vitest';++// Execute the page's callbacks with its host boundaries injected. Pure card+// copy/layout assertions were duplicates of rendering, i18n and layout suites.+// These regressions need the page's async scope and returned-message handling.+const page = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function findNode<T extends ts.Node>(find: (node: ts.Node) => node is T): T {+ let result: T | undefined;+ function visit(node: ts.Node) {+ if (find(node)) result = node;+ ts.forEachChild(node, visit);+ }+ visit(page);+ if (!result) throw new Error('Missing production session behavior');+ return result;+}+function evaluate(expression: ts.Expression, bindings: Record<string, unknown>): any {+ const code = ts.transpileModule('const value = ' + expression.getText(page), { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;+ return new Function(...Object.keys(bindings), code + '\nreturn value;')(...Object.values(bindings));+}+function variable(name: string): ts.Expression {+ const declaration = findNode((node): node is ts.VariableDeclaration => ts.isVariableDeclaration(node) && node.name.getText(page) === name);+ if (!declaration.initializer) throw new Error('Missing production initializer: ' + name);+ return declaration.initializer;+}+function callback(name: string, bindings: Record<string, unknown>): (...args: any[]) => any {+ const initializer = variable(name);+ if (!ts.isCallExpression(initializer)) throw new Error('Expected production useCallback: ' + name);+ return evaluate(initializer.arguments[0], bindings);+}+function effect(dependencies: string[], bindings: Record<string, unknown>): () => void {+ const call = findNode((node): node is ts.CallExpression => ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'useEffect'+ && node.arguments.length > 1 && ts.isArrayLiteralExpression(node.arguments[1]) && node.arguments[1].elements.map(item => item.getText(page)).join(',') === dependencies.join(','));+ return evaluate(call.arguments[0], bindings);+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>(done => { resolve = done; });+ return { promise, resolve };+}+function containingCondition(node: ts.Node): ts.ConditionalExpression {+ let current: ts.Node | undefined = node.parent;+ while (current && !ts.isConditionalExpression(current)) current = current.parent;+ if (!current) throw new Error('Missing production state branch');+ return current as ts.ConditionalExpression;+}++describe('mobile session page async controls', () => {+ it('replaces revoked shared content with the ended state and suppresses retry controls', () => {+ const ended = findNode((node): node is ts.JsxSelfClosingElement => ts.isJsxSelfClosingElement(node) && node.tagName.getText(page) === 'SharedTaskEndedState');+ const banner = findNode((node): node is ts.JsxSelfClosingElement => ts.isJsxSelfClosingElement(node) && node.tagName.getText(page) === 'ConnectionBanner');+ const replace = vi.fn();+ const bindings = { React, isSharedTaskAccessRevoked: true, ScrollView: 'ScrollView', SharedTaskEndedState: 'Ended',+ topOverlayHeight: 30, spacing: { lg: 16 }, router: { replace } };+ const tree = evaluate(containingCondition(ended), bindings);+ expect(tree.props.children.type).toBe('Ended');+ tree.props.children.props.onReturnToTasks();+ expect(replace).toHaveBeenCalledExactlyOnceWith('/devices');+ expect(evaluate(containingCondition(banner), bindings)).toBeNull();});- it('keeps the unsynced session state focused on the current action', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- const routeStart = source.indexOf('<SessionHeaderBar');- const routeEnd = source.indexOf('</View>', source.indexOf('<ConnectionBanner', routeStart));- const routeSource = source.slice(routeStart, routeEnd);- const syncStart = source.indexOf('function SessionSyncPlaceholder');- const syncEnd = source.indexOf('function MessageHistoryToggle', syncStart);- const syncSource = source.slice(syncStart, syncEnd);-- // banner 渲染条件(useShowConnectionBanner):请求级 / transport hold error、可分类连接问题、- // 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线经防闪窗口后也显示,不再彻底静默。- // Confirmed shared-task revocation has its own state, not a retry banner.- expect(routeSource).toContain('{!isSharedTaskAccessRevoked && (showConnectionBanner || showCachedHistoryNotice) ? (');- const revokedStart = source.indexOf('{isSharedTaskAccessRevoked ? (');- expect(revokedStart).toBeGreaterThan(-1);- const revokedEnd = source.indexOf("sessionOperationLayout.composerSlot === 'missing-session'", revokedStart);- expect(revokedEnd).toBeGreaterThan(revokedStart);- expect(source.slice(revokedStart, revokedEnd)).toContain('paddingTop: topOverlayHeight + spacing.lg');- expect(source.slice(revokedStart, revokedEnd)).toContain('<SharedTaskEndedState');- expect(source.slice(revokedStart, revokedEnd)).toContain("router.replace('/devices')");- expect(routeSource).toContain('cachedOnly={showCachedHistoryNotice}');- expect(source.replace(/\r\n/g, '\n'))- .toContain('useShowConnectionBanner(\n status,\n bannerError,');- expect(routeSource).not.toContain('connectionError || (loading && !currentSession)');- expect(syncSource).toContain("t('session.screen.awaitingSync')");- expect(syncSource).toContain("t('session.screen.resync')");- expect(syncSource).toContain('RefreshCw');- expect(syncSource).toContain('sessionSyncRow');- expect(syncSource).not.toContain('上方同步成功后');- expect(source).not.toContain('同步成功后可继续发送');- expect(syncSource).not.toContain('手机端的会话内容显示在这里');- expect(source).not.toContain('sessionSyncText');- expect(source).not.toContain('sessionSyncCard');- expect(source).not.toContain('sessionSyncButtonText');- expect(source).not.toContain('testID="session.noSessionComposer"');- expect(source).not.toContain('testID="session.noSessionSyncButton"');- expect(source).not.toContain('unsyncedComposerButtonText');+ it.each(['unchanged', 'sessionId', 'deviceId', 'accountProviderId'])('suppresses stale reset alerts when refresh changes %s', async (changed) => {+ const identity = { deviceId: 'd1', sessionId: 's1', accountProviderId: 'openai' };+ const scope = evaluate(variable('accountControlScope'), identity);+ const accountControlScopeRef = { current: scope };+ const refresh = deferred<void>();+ const alert = vi.fn();+ const clearRetry = vi.fn();+ const reset = callback('resetCodexRateLimits', { codexRateLimits: null, codexResetRetryKey: 'expired-offer', codexResetBusy: false,+ setCodexResetRetryKey: clearRetry, refreshAccountUsage: () => refresh.promise, accountControlScopeRef, accountControlScope: scope,+ Alert: { alert }, t: (key: string) => key });+ const pending = reset();+ expect(clearRetry).toHaveBeenCalledExactlyOnceWith(null);+ expect(alert).not.toHaveBeenCalled();+ if (changed !== 'unchanged') accountControlScopeRef.current = evaluate(variable('accountControlScope'), { ...identity, [changed]: 'changed' });+ refresh.resolve();+ await pending;+ if (changed === 'unchanged') expect(alert).toHaveBeenCalledExactlyOnceWith('session.screen.resetReconfirmTitle', 'session.screen.resetOfferExpired');+ else expect(alert).not.toHaveBeenCalled();});- it('does not pin collaboration explanatory copy above the message stream', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- const mainStart = source.indexOf('<View style={styles.sessionMainLayer}');- const mainEnd = source.indexOf('<View style={styles.sessionBottomLayer}', mainStart);- const mainSource = source.slice(mainStart, mainEnd);-- expect(mainSource).not.toContain('协作会话');- expect(mainSource).not.toContain('session.collaborationBanner');- expect(source).not.toContain('sessionCollaborationNotice');- expect(source).not.toContain('collaborationBanner');+ it.each([+ { result: { clientIds: ['part-1', '', null, 'part-2', 42] }, removed: ['part-1', 'part-2'] },+ { result: { clientIds: [] }, removed: ['requested'] },+ { result: {}, removed: ['requested'] },+ ])('applies the host deletion group, with legacy fallback: $removed', async ({ result, removed }) => {+ const hostResult = deferred<typeof result>();+ const removeMessages = vi.fn();+ const hostDelete = vi.fn(() => hostResult.promise);+ const busy = vi.fn();+ const alert = vi.fn();+ const remove = callback('deleteMessage', { deviceId: 'd1', sessionId: 's1', messageActionBusy: null,+ Alert: { alert }, t: (key: string) => key, maker: { deleteMessage: hostDelete }, remoteSessionStore: { removeMessages },+ setMessageActionBusy: busy, setError: vi.fn() });+ remove('requested');+ expect(hostDelete).not.toHaveBeenCalled();+ const actions = alert.mock.calls[0][2] as { style: string; onPress?: () => void }[];+ actions.find(action => action.style === 'destructive')!.onPress!();+ expect(hostDelete).toHaveBeenCalledExactlyOnceWith('s1', 'requested');+ expect(removeMessages).not.toHaveBeenCalled();+ hostResult.resolve(result);+ await hostResult.promise;+ expect(removeMessages).toHaveBeenCalledExactlyOnceWith('s1', removed, 'd1');+ expect(busy.mock.calls).toEqual([[{ clientId: 'requested', kind: 'delete' }], [null]]);});- it('lets collaboration sessions operate like regular tasks on mobile', () => {- // Windows checkout 使用 CRLF;源码契约中的多行 LF 片段必须先统一行尾再比较。- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8')- .replace(/\r\n/g, '\n');-- // 协同任务(Lead / Worker)不再有只读通道:输入框、队列、确认、设置、fork/rewind 与普通任务一致。- expect(source).not.toContain('collaborationReadOnlyReason');- expect(source).not.toContain('composerReadOnlyReason');- expect(source).not.toContain("composerSlot === 'read-only'");- // 「会话参数未就绪」的两条理由(缓存种入 / 新建在途)只留给队列行操作,不锁输入框。- expect(source).toContain('const queueAvailabilityReason = cacheSeededReason\n ?? pendingCreationReason');- expect(source).toContain('readOnlyReason={queueAvailabilityReason}');- // header notice:协同任务显示协同标签。- expect(source).toContain('const collaborationLabel = sessionCollaborationLabel(session);');- expect(source).toContain('if (collaborationLabel) return collaborationLabel;');- expect(source).toContain('onForkMessage={isSharedTaskPeer(deviceId) ? undefined : forkAtMessage}');- expect(source).toContain('onPreviewRewind={isSharedTaskPeer(deviceId) ? undefined : previewRewindAtMessage}');+ it('resyncs once per recovered online connection without reloading on unchanged ticks', () => {+ const bindings = { connectionEpoch: 1, status: 'online', syncedConnectionEpochRef: { current: 1 }, latchOutboxTransportHold: vi.fn(), load: vi.fn() };+ const run = () => effect(['connectionEpoch', 'latchOutboxTransportHold', 'load', 'status'], bindings)();+ run();+ bindings.connectionEpoch = 2; bindings.status = 'offline'; run();+ expect(bindings.load).not.toHaveBeenCalled();+ bindings.status = 'online'; run(); run();+ expect(bindings.load).toHaveBeenCalledTimes(1);+ expect(bindings.latchOutboxTransportHold).toHaveBeenCalledExactlyOnceWith(null);});- it('resyncs sessions from connection recovery or target availability, not every presence tick', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- expect(source).toContain('connectionEpoch');- expect(source).toContain('getPresenceAvailability(deviceId)');- expect(source).toContain('targetAvailableRef');- expect(source).toContain('wasAvailable !== true');- expect(source).not.toContain('lastPresenceSnapshot');- expect(source).not.toContain('presenceVersion');+ it('resyncs only a same-device availability recovery and leaves initial or switched devices to mount', () => {+ const bindings = { deviceId: 'd1', targetAvailableDeviceRef: { current: null as string | null }, targetAvailableRef: { current: null as boolean | null },+ targetAvailableForDispatch: true as boolean | null, status: 'online', latchOutboxTransportHold: vi.fn(), load: vi.fn() };+ const run = () => effect(['deviceId', 'latchOutboxTransportHold', 'load', 'status', 'targetAvailableForDispatch'], bindings)();+ run(); run();+ bindings.deviceId = 'd2'; run();+ expect(bindings.load).not.toHaveBeenCalled();+ bindings.targetAvailableForDispatch = false; run();+ bindings.targetAvailableForDispatch = true; run(); run();+ expect(bindings.load).toHaveBeenCalledTimes(1);});- it('drops stale Codex reset alerts after the active session changes during refresh', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- const resetStart = source.indexOf('const resetCodexRateLimits');- const resetEnd = source.indexOf('const loadExtraDirBrowsePath', resetStart);- const resetSource = source.slice(resetStart, resetEnd);- const staleOfferStart = resetSource.indexOf('if (!offer');- const refresh = resetSource.indexOf('await refreshAccountUsage();', staleOfferStart);- const sessionGuard = resetSource.indexOf(- 'if (accountControlScopeRef.current !== accountControlScope) return;',- refresh,- );- const alert = resetSource.indexOf("Alert.alert(t('session.screen.resetReconfirmTitle'), t('session.screen.resetOfferExpired'))", refresh);-- expect(source).toContain('const accountControlScope = `${deviceId}\\0${sessionId}\\0${accountProviderId}`;');- expect(refresh).toBeGreaterThan(-1);- expect(sessionGuard).toBeGreaterThan(refresh);- expect(alert).toBeGreaterThan(sessionGuard);- });-- it('keeps session sheets titled by user-facing desktop concepts only', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- // 消息队列已从独立弹层退役,inline 到消息流(InlineQueueSection),不再有 sheet 标题。- expect(source).not.toContain('消息队列');- expect(source).toContain("t('session.screen.searchTitle')");- expect(source).not.toContain('REMOTE QUEUE');- expect(source).not.toContain('MESSAGE SEARCH');- expect(source).not.toContain('queueSheetEyebrow');- expect(source).not.toContain('searchSheetEyebrow');- });-- it('mirrors the complete grouped deletion returned by the desktop host', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- const deleteStart = source.indexOf('const deleteMessage = useCallback');- const deleteEnd = source.indexOf('const confirmRewind', deleteStart);- const deleteSource = source.slice(deleteStart, deleteEnd);-- expect(deleteSource).toContain("Alert.alert(t('session.screen.deleteMessageTitle')");- expect(deleteSource).toContain("t('session.screen.deleteMessageBody')");- expect(deleteSource).toContain('const result = await maker.deleteMessage(sessionId, clientId);');- expect(deleteSource).toContain('Array.isArray(result.clientIds)');- expect(deleteSource).toContain('remoteSessionStore.removeMessages(');- expect(deleteSource).toContain('returnedClientIds.length > 0 ? returnedClientIds : [clientId]');- });-- it('renders system cards by their desktop title without a generic debug eyebrow', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const desktopSource = readFileSync(resolve(process.cwd(), '../../apps/desktop/src/renderer/components/chat/SystemCard.tsx'), 'utf8');- const cardStart = source.indexOf('function MobileSystemCard');- const cardEnd = source.indexOf('function MarkdownBody', cardStart);- const cardSource = source.slice(cardStart, cardEnd);-- expect(desktopSource).toContain('const titleClass');- expect(desktopSource).not.toContain('SYSTEM');- expect(cardSource).toContain('<Text style={styles.systemCardTitle}>{card.title}</Text>');- expect(cardSource).toContain('function MobileAutoResumeActionRow');- expect(cardSource).toContain('message.systemCard.autoResume.detail.reason');- expect(cardSource).toContain('message.systemCard.autoResume.detail.attempt');- expect(cardSource).toContain('message.systemCard.autoResume.detail.sessionTotal');- expect(cardSource).toContain('CompactActivityIndicator');- expect(cardSource).toContain('message.systemCard.autoResume.pendingWithProgress');- expect(cardSource).toContain('importantForAccessibility="no-hide-descendants"');- expect(cardSource).toContain('accessible={false}');- expect(source).toMatch(/autoResumeHeader:\s*\{[\s\S]*?minHeight:\s*44,/);- expect(cardSource).not.toContain('SYSTEM');- expect(cardSource).not.toContain('systemCardEyebrow');- expect(source).not.toContain('systemCardEyebrow: {');+ it.each([false, true])('restricts fork and rewind actions for shared-task peers=%s', (shared) => {+ const forkAtMessage = vi.fn(); const previewRewindAtMessage = vi.fn();+ const bindings = { deviceId: 'd1', isSharedTaskPeer: () => shared, forkAtMessage, previewRewindAtMessage };+ for (const [prop, handler] of [['onForkMessage', forkAtMessage], ['onPreviewRewind', previewRewindAtMessage]] as const) {+ const attribute = findNode((node): node is ts.JsxAttribute => ts.isJsxAttribute(node) && node.name.getText(page) === prop);+ if (!attribute.initializer || !ts.isJsxExpression(attribute.initializer) || !attribute.initializer.expression) throw new Error('Missing page action binding: ' + prop);+ const action = evaluate(attribute.initializer.expression, bindings);+ if (shared) expect(action).toBeUndefined();+ else { action('m1'); expect(handler).toHaveBeenCalledExactlyOnceWith('m1'); }+ }});});diff --git a/apps/mobile/src/__tests__/sessionOperationLayout.test.ts b/apps/mobile/src/__tests__/sessionOperationLayout.test.tsindex 4ee9830afa..86fddf9181 100644--- a/apps/mobile/src/__tests__/sessionOperationLayout.test.ts+++ b/apps/mobile/src/__tests__/sessionOperationLayout.test.ts@@ -1,5 +1,6 @@import { readFileSync } from "node:fs";import { resolve } from "node:path";+import ts from 'typescript';import { beforeAll, describe, expect, it } from "vitest";import { i18n } from "@/i18n";import {@@ -167,10 +168,22 @@ describe("session operation layout", () => {resolve(process.cwd(), "app/sessions/[sessionId].tsx"),"utf8",);- expect(sessionScreenSource).toContain("composerDisabledReasonI18nKey(");- expect(sessionScreenSource).not.toContain(- "sessionOperationLayout.composerDisabledReason}",- );+ const tree = ts.createSourceFile('session.tsx', sessionScreenSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const expressions = new Map<string, ts.Expression>();+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.initializer) expressions.set(node.name.getText(tree), node.initializer);+ ts.forEachChild(node, visit);+ }+ visit(tree);+ const key = expressions.get('composerDisabledReasonKey');+ const reason = expressions.get('composerDisabledReason');+ if (!key || !reason) throw new Error('Missing production composer disabled reason');+ const renderReason = new Function('sessionOperationLayout', 'composerDisabledReasonI18nKey', 'companionEntry', 'sessionResourceCards', 't',+ `const composerDisabledReasonKey = ${key.getText(tree)}; return (${reason.getText(tree)});`);+ for (const source of ['session-syncing', 'pending-interaction'] as const) {+ expect(renderReason({ composerDisabledReasonSource: source, composerDisabledReason: 'untranslated' }, composerDisabledReasonI18nKey, { canCompose: true }, { blocked: false }, (key: string) => 'translated:' + key))+ .toBe('translated:' + composerDisabledReasonI18nKey(source));+ }});it("shows queue and composer for normal writable sessions", () => {diff --git a/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts b/apps/mobile/src/__tests__/sessionScreenshotShare.test.tsindex df5924dcb0..f0088b577d 100644--- a/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts+++ b/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts@@ -1,3 +1,4 @@+// guard: engineering-conventions.md 3.2 race contract: overlay ownership and selection revisions fence the screenshot listener and asynchronous exporter across renderer/page boundaries.import { readFileSync } from "node:fs";import { resolve } from "node:path";import { describe, expect, it } from "vitest";diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.tsindex bd2cbea73b..eece9f1c3e 100644--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts@@ -6,6 +6,7 @@ import { createRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import { runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';import { shouldClearOperationErrorAfterSync } from '@/session/sessionSyncErrorRecovery';+import { resolveEffectiveConnectionError } from '@/components/connectionBannerVisibility';import {bridgeLatestMessagePage,hasOlderMessagesAfterReopen,@@ -295,16 +296,18 @@ describe('production session recovery callbacks', () => {});it('routes the visible history retry to pagination rather than full sync', () => {- const screen = source.getFullText().replace(/\r\n/g, '\n');- expect(screen).toContain('const bannerError = connectionRecoveryError ?? historyError;');- expect(screen).toContain('const bannerRetriesHistory = connectionRecoveryError === null && historyError !== null;');- expect(screen).toContain('requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}');- expect(screen).toContain('loading={loading || loadingEarlier}');+ const values = new Map<string, ts.Expression>();+ const props = new Map<string, ts.Expression>();let onSync: ts.Expression | undefined;const find = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.initializer) values.set(node.name.getText(source), node.initializer);if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'ConnectionBanner') {- const prop = node.attributes.properties.find(p => ts.isJsxAttribute(p) && p.name.getText(source) === 'onSync') as ts.JsxAttribute;- onSync = (prop.initializer as ts.JsxExpression).expression;+ for (const prop of node.attributes.properties) {+ if (ts.isJsxAttribute(prop) && prop.initializer && ts.isJsxExpression(prop.initializer) && prop.initializer.expression) {+ props.set(prop.name.getText(source), prop.initializer.expression);+ }+ }+ onSync = props.get('onSync');}ts.forEachChild(node, find);};@@ -315,8 +318,25 @@ describe('production session recovery callbacks', () => {expect(loadEarlierMessages).toHaveBeenCalledOnce(); expect(requestSync).not.toHaveBeenCalled(); expect(retry).not.toHaveBeenCalled();run(false, { error: 'lookup failed', retry }, loadEarlierMessages, requestSync);expect(retry).toHaveBeenCalledOnce(); expect(requestSync).toHaveBeenCalledExactlyOnceWith({ reason: 'manual', replaceMessages: false });- const errorSources = screen.slice(screen.indexOf('const connectionError ='), screen.indexOf('const bannerError ='));- expect(errorSources).not.toContain('historyError');+ function evaluate(expression: ts.Expression | undefined, bindings: Record<string, unknown>) {+ if (!expression) throw new Error('Missing production banner expression');+ return new Function(...Object.keys(bindings), `return (${expression.getText(source)});`)(...Object.values(bindings));+ }+ for (const historyError of [null, 'earlier page failed']) {+ for (const connectionFailure of [null, 'connection failed']) {+ const connectionError = evaluate(values.get('connectionError'), { historyError, isDeviceAccessRevoked: false, syncError: connectionFailure, error: null, isDeviceUnresponsive: false, resolveEffectiveConnectionError });+ expect(connectionError).toBe(connectionFailure);+ const connectionRecoveryError = evaluate(values.get('connectionRecoveryError'), { companionEntry: { error: null }, activeOutboxTransportError: null, connectionError });+ const bannerError = evaluate(values.get('bannerError'), { connectionRecoveryError, historyError });+ const bannerRetriesHistory = evaluate(values.get('bannerRetriesHistory'), { connectionRecoveryError, historyError });+ expect(bannerError).toBe(connectionFailure ?? historyError);+ expect(bannerRetriesHistory).toBe(connectionFailure === null && historyError !== null);+ expect(evaluate(props.get('requestErrorAutoRecovering'), { bannerRetriesHistory })).toBe(bannerRetriesHistory ? false : undefined);+ }+ }+ for (const loading of [false, true]) for (const loadingEarlier of [false, true]) {+ expect(evaluate(props.get('loading'), { loading, loadingEarlier })).toBe(loading || loadingEarlier);+ }});it.each([false, true])('keeps late history and pagination after projection rejects (reopen=%s)', async (reopen) => {diff --git a/apps/mobile/src/__tests__/sessionToolIconDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionToolIconDesktopFirst.test.tsdeleted file mode 100644index 88d1ab7eb1..0000000000--- a/apps/mobile/src/__tests__/sessionToolIconDesktopFirst.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';--describe('desktop-first mobile tool icons', () => {- it('keeps search navigation as compact icon controls and sheets without root close buttons', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');-- expect(source).toContain('ChevronDown');- expect(source).toContain('ChevronUp');- expect(source).toContain('<ChevronUp color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />');- expect(source).toContain('<ChevronDown color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />');- expect(source).toContain('testID="session.searchPreviousButton"');- expect(source).toContain('testID="session.searchNextButton"');- // 底部 sheet 统一 SheetModal 外壳(背板淡入 + 面板滑入),根级关闭 X 移除:- // 把手下拉 / 点背板关闭已足够,队列 / 搜索 sheet 只保留视觉把手- // (把手收敛为 SheetSurface 导出的共享 SheetGrabber 组件)。- expect(source).toContain('<SheetModal');- expect(source).toContain('<SheetGrabber');- expect(source).not.toContain('sheetCloseButton');- expect(source).not.toContain('testID="queue.closeButton"');- expect(source).not.toContain('testID="session.searchCloseButton"');- expect(source).not.toContain('searchNavText');- expect(source).not.toContain('>关闭</Text>');- expect(source).not.toContain('>上一条</Text>');- expect(source).not.toContain('>下一条</Text>');- });-});diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.tsindex a42377c949..3022bfdef0 100644--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts@@ -1,95 +1,142 @@import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { posix, resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import { describe, expect, it, vi } from 'vitest';+import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';+import { resolvePnpmInvocation, usablePnpmExecPath } from '../../../../scripts/shared/pnpm-invocation.mjs';+import { extractMobileDevRegionArgs, withLocalMobileRegionConfig } from '../../scripts/lib/mobile-dev-region.mjs';+import { extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget, resolveMobileSimulatorBundleId } from '../../scripts/lib/sim-whoami.mjs';-// sim-rebuild.mjs 是纯 dev 工具脚本(依赖 booted 模拟器 + Xcode,无法在 CI 里真跑),-// 用源码检查锁住两个提速机制的关键不变量,防止后续改动无意退化:-// 1. pod install 必须有界(超时 + SIGKILL)且显式 UTF-8 LANG —— 曾发生 CDN 连接-// 挂死干等 20 分钟、以及空 LANG 触发 CocoaPods Encoding::CompatibilityError。-// 2. fingerprint 产物缓存 —— 新 worktree 未动原生层时跳过整个冷构建。-describe('sim-rebuild script invariants', () => {- const source = readFileSync(resolve(process.cwd(), 'scripts/sim-rebuild.mjs'), 'utf8');+const source = readFileSync(resolve(process.cwd(), 'scripts/sim-rebuild.mjs'), 'utf8');+const start = source.indexOf('const iosDir =');+if (start < 0) throw new Error('sim-rebuild workflow entry missing');+const mobileDir = '/repo/apps/mobile';+const cacheRoot = '/home/test/Library/Caches/xdt-maker/sim-app-cache';+const cacheDir = `${cacheRoot}/ios-arm64-fingerprint`;+const builtApp = `${mobileDir}/ios/build/Build/Products/Debug-iphonesimulator/Cindy.app`;+const udid = '11111111-1111-1111-1111-111111111111';- it('runs pod install itself via the bounded runner, instead of letting prebuild own it', () => {- expect(source).toContain('const buildEnv = withLocalMobileRegionConfig(');- // prebuild 不再隐式跑 pod install(它的失败重试会带 --repo-update 打 CDN 且无界)。- expect(source).toContain("['exec', 'expo', 'prebuild', '-p', 'ios', '--no-install']");- // pod 执行策略(本地 specs 优先 / --repo-update 重试 / 空转看门狗 / UTF-8 LANG)- // 收敛在 sim-pod-install.mjs,行为由 simPodInstall.test.ts 用假 pod 二进制真实覆盖。- expect(source).toContain("import { podInstallBounded } from './sim-pod-install.mjs';");- expect(source).toContain('await podInstallBounded({ iosDir, env: devProcessEnv })');+// Execute the real CLI workflow with in-memory filesystem and process boundaries.+// simPodInstall and simNativeIdentity suites cover their real implementations separately.+async function rebuild(options: {+ args?: string[]; platform?: 'darwin' | 'win32'; cached?: boolean; cachedArch?: string;+ fingerprintFailure?: boolean; metroHealthy?: boolean; builtArch?: string;+} = {}) {+ const env = { EXPO_PUBLIC_APP_VARIANT: 'beta', npm_execpath: '/tools/pnpm.cjs' };+ const processStub = {+ argv: ['node', 'sim-rebuild.mjs', ...(options.args ?? [])], env,+ platform: options.platform ?? 'darwin', arch: 'arm64', execPath: '/node', exitCode: 0,+ exit(code: number) { throw new Error(`exit:${code}`); },+ };+ const execFileSync = vi.fn((command: string, args: string[], _opts: object) => {+ if (command === 'plutil') return args[1] === 'CFBundleIdentifier' ? 'com.xd.cindy' : 'Cindy';+ if (command === 'lipo') return args[1].startsWith(cacheRoot) ? (options.cachedArch ?? 'arm64') : (options.builtArch ?? 'arm64');+ if (command === '/node' && args.includes('config')) return JSON.stringify({ android: { package: 'com.xd.cindy' } });+ if (command === 'xcrun' && args.includes('get_app_container')) return '/installed/Cindy.app';+ if (command === 'xcrun' && args.includes('booted')) return `iPhone (${udid}) (Booted)`;+ if (['pnpm', '/node', 'xcodebuild', 'cmd.exe', '/sdk/adb', 'xcrun'].includes(command)) return '';+ throw new Error(`unexpected executable ${command}`);});+ const spawnSync = vi.fn((_command: string, _args: string[], _opts: { env: object }) => ({ status: 0, stdout: JSON.stringify({ hash: 'fingerprint' }) }));+ const podInstallBounded = vi.fn(async () => undefined);+ const rmSync = vi.fn();+ const cpSync = vi.fn();+ const writeFileSync = vi.fn();+ const utimesSync = vi.fn();+ const now = Date.now();+ const cacheEntries = ['recent0', 'recent1', 'recent2', 'recent3', 'young', 'old'];+ const validateSimMetroIdentity = vi.fn(() => ({ healthy: options.metroHealthy !== false, code: 'METRO_OTHER_WORKTREE' }));+ const resolveAndroidSdkTools = vi.fn(() => ({ sdkRoot: '/sdk' }));+ const ensureWindowsAndroidEmulator = vi.fn(async () => ({ sdkRoot: '/sdk', adb: '/sdk/adb', serial: 'emulator-5554' }));+ const javaEnv = { ...env, JAVA_HOME: '/jdk17', ANDROID_SDK_ROOT: '/sdk', ANDROID_HOME: '/sdk' };+ const resolveJavaRuntimeEnv = vi.fn(() => javaEnv);+ const log = vi.fn();+ const execution = runInNewContext(`(async () => { ${source.slice(start)} })()`, {+ mobileDir, worktreeRoot: '/repo', join: posix.join, resolve: posix.resolve, homedir: () => '/home/test',+ process: processStub, console: { log, error: log, warn: log }, execFileSync, spawnSync,+ mobileClientBundleEnv, extractMobileDevRegionArgs, withLocalMobileRegionConfig,+ extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget,+ resolveMobileSimulatorBundleId: (region: string) => resolveMobileSimulatorBundleId(region, { execFile: () => JSON.stringify({ ios: { bundleIdentifier: 'com.xd.cindy' } }) }),+ resolvePnpmInvocation: (args: string[], opts: object) => resolvePnpmInvocation(args, { ...opts, platform: processStub.platform, execPath: '/node' }),+ usablePnpmExecPath, ensureMobileLocalRegionConfig: () => ({}), formatMobileLocalConfigStatus: () => '',+ ensureMobileEnv: () => ({ created: false, addedKeys: [] }), formatMobileEnvStatus: () => '',+ computeSimulatorNativeFingerprint: () => 'native-fingerprint', inspectSimulatorNativeIdentity: () => ({ healthy: true }),+ computeFingerprintReport: (_dir: string, opts: { run: (input: object) => { hash: string } }) => {+ if (options.fingerprintFailure) throw new Error('fingerprint unavailable');+ return { platforms: { ios: opts.run({ binPath: '/fingerprint/cli.js', projectDir: mobileDir, platform: 'ios' }).hash } };+ },+ parseFingerprintCliOutput: JSON.parse, podInstallBounded,+ existsSync: () => true, mkdirSync: vi.fn(), rmSync, cpSync, writeFileSync, utimesSync,+ readFileSync: (path: string) => {+ if (!options.cached || path !== `${cacheDir}/meta.json`) throw new Error('cache miss');+ return JSON.stringify({ scheme: 'Cindy' });+ },+ readdirSync: (path: string) => path === `${mobileDir}/ios` ? ['Cindy.xcworkspace'] : cacheEntries,+ statSync: (path: string) => ({ isDirectory: () => true, mtimeMs: now - (path.endsWith('/old') ? 3_600_000 : cacheEntries.indexOf(posix.basename(path)) * 1000) }),+ resolveAndroidSdkTools, ensureWindowsAndroidEmulator, resolveJavaRuntimeEnv,+ probeMetroOwnership: () => ({ cwd: mobileDir, source: 'same', region: 'global', envFingerprint: 'same-env' }),+ readSimEnvironment: () => ({ envFingerprint: 'same-env' }), gitSourceIdentity: () => 'same',+ classifySimMetroListener: (input: object) => input, validateSimMetroIdentity,+ });+ let error: unknown;+ try { await execution; } catch (caught) { error = caught; }+ return { error, execFileSync, spawnSync, podInstallBounded, rmSync, cpSync, writeFileSync, utimesSync, validateSimMetroIdentity, resolveAndroidSdkTools, ensureWindowsAndroidEmulator, resolveJavaRuntimeEnv, javaEnv, log };+}- it('reuses built .app via the @expo/fingerprint cache with a force-build escape hatch', () => {- // 计算失败必须降级为完整构建而不是中断。- expect(source).toContain('回退完整构建');- // 缓存键必须用**当前环境**算 fingerprint:ci-fingerprint 默认 runner 是- // production 口径(剥离 EXPO_PUBLIC_*),而 prebuild 继承当前环境,beta 变体- // (EXPO_PUBLIC_APP_VARIANT)会改原生 name——不跟 env 走会互相污染缓存。- expect(source).toContain('run: runFingerprintWithCurrentEnv');- expect(source).toContain('env: devProcessEnv');- // --force-build 只跳过缓存"读",构建结果仍写回同一条目覆盖坏缓存;- // 否则逃生舱跑完一次,坏条目还在,下次普通 rebuild 又命中它。- expect(source).toContain("passthrough.includes('--force-build')");- expect(source).toContain('if (cacheDir && !forceBuild) {');- expect(source).toContain(- 'if (cacheDir) storeAppCacheEntry(cacheDir, scheme, app, readAppBundleIdentifier(app));',- );- // global 产物的 bundle id 不同于 app.json 默认 cn 值,必须从实际 .app 读。- expect(source).toContain("'CFBundleIdentifier'");- expect(source).toContain('const bundleId = readAppBundleIdentifier(app);');- expect(source).toContain('readAppCacheEntry(cacheDir, simArch)');- expect(source).toContain('assertAppSupportsArchitecture(app, simArch)');- expect(source).toContain("capture('lipo', ['-archs'");- // 缓存条目按 fingerprint + 架构定位,meta.json 是条目完整性标记。- expect(source).toContain('sim-app-cache');- expect(source).toContain('ios-${simArch}-${fingerprintHash}');- expect(source).toContain("join(dir, 'meta.json')");- // 有上限的 LRU 清理,不能无限积累 .app;且带最小年龄护栏,不删可能正被- // 另一个并发 rebuild 使用的条目(命中方会先 touch mtime)。- expect(source).toContain('APP_CACHE_KEEP');- expect(source).toContain('entries.slice(APP_CACHE_KEEP)');- expect(source).toContain('APP_CACHE_PRUNE_MIN_AGE_MS) continue;');+describe('sim-rebuild workflow', () => {+ it.each([false, true])('reuses valid cache and writes force-built artifacts back (force=%s)', async (force) => {+ const result = await rebuild({ cached: true, args: ['--build-only', ...(force ? ['--force-build', '--udid', udid] : [])] });+ expect(result.error).toEqual(new Error('exit:0'));+ expect(result.podInstallBounded).toHaveBeenCalledTimes(force ? 1 : 0);+ expect(result.execFileSync.mock.calls.some(([cmd]) => cmd === 'xcodebuild')).toBe(force);+ const fingerprintEnv = result.spawnSync.mock.calls[0][2].env;+ expect(fingerprintEnv).toMatchObject({ EXPO_PUBLIC_APP_VARIANT: 'beta', CINDY_USE_LOCAL_REGION_CONFIG: '1' });+ if (force) {+ expect(result.execFileSync).toHaveBeenCalledWith('pnpm', ['exec', 'expo', 'prebuild', '-p', 'ios', '--no-install'], expect.objectContaining({ env: fingerprintEnv }));+ expect(result.podInstallBounded).toHaveBeenCalledWith({ iosDir: `${mobileDir}/ios`, env: fingerprintEnv });+ expect(result.execFileSync).toHaveBeenCalledWith('xcodebuild', expect.arrayContaining(['-destination', `platform=iOS Simulator,id=${udid}`]), expect.objectContaining({ env: fingerprintEnv }));+ expect(result.cpSync).toHaveBeenCalledWith(builtApp, `${cacheDir}/Cindy.app`, expect.any(Object));+ expect(JSON.parse(result.writeFileSync.mock.calls[0][1])).toMatchObject({ scheme: 'Cindy', bundleId: 'com.xd.cindy' });+ expect(result.cpSync.mock.invocationCallOrder[0]).toBeLessThan(result.writeFileSync.mock.invocationCallOrder[0]);+ expect(result.rmSync).toHaveBeenCalledWith(`${cacheRoot}/old`, { recursive: true, force: true });+ expect(result.rmSync).not.toHaveBeenCalledWith(`${cacheRoot}/young`, expect.anything());+ } else {+ expect(result.utimesSync).toHaveBeenCalledWith(cacheDir, expect.anything(), expect.anything());+ expect(result.utimesSync.mock.calls[0][1].getTime()).toBeGreaterThan(0);+ expect(result.cpSync).not.toHaveBeenCalled();+ }+ expect(result.execFileSync.mock.calls.some(([cmd]) => cmd === 'xcrun')).toBe(false);});- it('uses an exact simulator destination when the Host supplies a UDID', () => {- expect(source).toContain('const { simulatorUdid } = extractSimWhoamiUdidArgs(passthrough);');- expect(source).toContain('`platform=iOS Simulator,id=${simulatorUdid}`');- expect(source).toContain("'-destination', simulatorDestination");+ it.each(['fingerprint-failure', 'cached-architecture-mismatch'])('falls back to a full build for %s', async (reason) => {+ const result = await rebuild({ args: ['--build-only'], cached: true, cachedArch: 'x86_64', fingerprintFailure: reason === 'fingerprint-failure' });+ expect(result.error).toEqual(new Error('exit:0'));+ expect(result.podInstallBounded).toHaveBeenCalledOnce();+ expect(result.execFileSync).toHaveBeenCalledWith('xcodebuild', expect.arrayContaining(['-destination', 'generic/platform=iOS Simulator']), expect.any(Object));+ expect(result.cpSync).toHaveBeenCalledTimes(reason === 'fingerprint-failure' ? 0 : 1);});- it('uses the Android debug client on Windows without invoking xcrun', () => {- expect(source).toContain("import { ensureWindowsAndroidEmulator, resolveAndroidSdkTools } from './lib/android-simulator.mjs';");- expect(source).toContain("probeMetroOwnership");- expect(source).toContain('const ownership = probeMetroOwnership(8081);');- expect(source).toContain('validateSimMetroIdentity');- expect(source).toContain('runningRegion: ownership?.region');- expect(source).toContain('if (!await ensureMetroOwnershipBeforeLaunch(bundleId)) process.exit(1)');- expect(source).toContain("import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';");- expect(source).toContain('const androidTools = process.platform === \'win32\'');- expect(source).toContain('requireTools: !buildOnly');- expect(source).toContain('ANDROID_SDK_ROOT: sdkRoot, ANDROID_HOME: sdkRoot');- expect(source).toContain("if (process.platform === 'win32') {");- expect(source).toContain('await rebuildAndroidSimulator();');- expect(source).toContain("'--platform', 'android', '--no-install'");- expect(source).toContain("const gradle = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';");- // Explicit cwd path also works with NoDefaultCurrentDirectoryInExePath enabled.- expect(source).toContain("run('cmd.exe', ['/d', '/s', '/c', '.\\\\gradlew.bat assembleDebug']");- expect(source).not.toContain('process.env.ComSpec');- expect(source).toContain('resolvePnpmInvocation');- expect(source).toContain('function runPnpm(args, opts = {})');- expect(source).toContain("run(gradle, ['assembleDebug']");- expect(source).toContain("'install', '-r', apk");- expect(source).toContain("'shell', 'monkey', '-p', packageName, '1'");- expect(source).toContain('function ensureMetroOwnershipBeforeLaunch(packageName)');- const metroGate = source.indexOf('if (!await ensureMetroOwnershipBeforeLaunch(packageName)) return;');- const androidLaunch = source.indexOf("'shell', 'monkey', '-p', packageName, '1'");- expect(metroGate).toBeGreaterThanOrEqual(0);- expect(metroGate).toBeLessThan(androidLaunch);+ it('rejects incompatible build architecture before installing on the simulator', async () => {+ const result = await rebuild({ builtArch: 'x86_64' });+ expect(result.error).toMatchObject({ message: expect.stringContaining('Simulator 产物架构错误') });+ expect(result.execFileSync.mock.calls.some(([, args]) => args.includes('install'))).toBe(false);+ });- const windowsBranch = source.indexOf("if (process.platform === 'win32') {");- const iosXcrunProbe = source.indexOf("capture('xcrun', ['simctl', 'list', 'devices', 'booted'])");- expect(windowsBranch).toBeGreaterThanOrEqual(0);- expect(iosXcrunProbe).toBeGreaterThan(windowsBranch);+ it.each([true, false])('checks Metro after Windows installation and before launch (healthy=%s)', async (healthy) => {+ const result = await rebuild({ platform: 'win32', metroHealthy: healthy });+ expect(result.error).toEqual(new Error(`exit:${healthy ? 0 : 1}`));+ expect(result.resolveAndroidSdkTools).toHaveBeenCalledWith(expect.objectContaining({ platform: 'win32', requireTools: true }));+ expect(result.resolveJavaRuntimeEnv).toHaveBeenCalledWith(expect.objectContaining({ ANDROID_SDK_ROOT: '/sdk', ANDROID_HOME: '/sdk', CINDY_USE_LOCAL_REGION_CONFIG: '1' }));+ expect(result.execFileSync).toHaveBeenCalledWith('/node', ['/tools/pnpm.cjs', 'exec', 'expo', 'prebuild', '--platform', 'android', '--no-install'], expect.any(Object));+ expect(result.execFileSync).toHaveBeenCalledWith('cmd.exe', ['/d', '/s', '/c', '.\\gradlew.bat assembleDebug'], expect.objectContaining({ cwd: `${mobileDir}/android`, env: result.javaEnv, windowsVerbatimArguments: true }));+ const install = result.execFileSync.mock.calls.findIndex(([, args]) => args.includes('install'));+ const launch = result.execFileSync.mock.calls.findIndex(([, args]) => args.includes('monkey'));+ expect(install).toBeGreaterThanOrEqual(0);+ expect(result.validateSimMetroIdentity).toHaveBeenCalledWith(expect.objectContaining({ currentRegion: 'global', runningRegion: 'global', currentEnvFingerprint: 'same-env', runningEnvFingerprint: 'same-env' }));+ expect(result.execFileSync.mock.invocationCallOrder[install]).toBeLessThan(result.validateSimMetroIdentity.mock.invocationCallOrder[0]);+ if (healthy) expect(result.validateSimMetroIdentity.mock.invocationCallOrder[0]).toBeLessThan(result.execFileSync.mock.invocationCallOrder[launch]);+ else expect(launch).toBe(-1);+ expect(result.execFileSync.mock.calls.some(([cmd]) => ['xcrun', 'xcodebuild'].includes(cmd))).toBe(false);+ expect(result.podInstallBounded).not.toHaveBeenCalled();});});diff --git a/apps/mobile/src/__tests__/splashPreview.test.ts b/apps/mobile/src/__tests__/splashPreview.test.tsindex 4d0613546e..d685c06c12 100644--- a/apps/mobile/src/__tests__/splashPreview.test.ts+++ b/apps/mobile/src/__tests__/splashPreview.test.ts@@ -1,55 +1,20 @@-import { existsSync, readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-describe('mobile splash preview route', () => {- it('is gated to dev visual mock and renders the production splash variant', () => {- const source = readFileSync(resolve(process.cwd(), 'app/splash-preview.tsx'), 'utf8');-- expect(source).toContain("import { Redirect } from 'expo-router';");- expect(source).toContain("import { CenteredScreen } from '@/components/CenteredScreen';");- expect(source).toContain("import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';");- expect(source).toContain('if (!MOBILE_VISUAL_MOCK_ENABLED) return <Redirect href="/" />;');- expect(source).toContain('<CenteredScreen title="Cindy" variant="splash" />');- expect(source).not.toContain('process.env.EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK');- });-- it('renders the splash variant through the wave4 brand host, not the legacy red splash assets', () => {- const source = readFileSync(resolve(process.cwd(), 'src/components/CenteredScreen.tsx'), 'utf8');+const state = vi.hoisted(() => ({ enabled: false }));+vi.mock('expo-router', () => ({ Redirect: 'Redirect' }));+vi.mock('@/components/CenteredScreen', () => ({ CenteredScreen: 'CenteredScreen' }));+vi.mock('@/config/env', () => ({+ get MOBILE_VISUAL_MOCK_ENABLED() { return state.enabled; },+}));+import SplashPreviewScreen from '../../app/splash-preview';- // PR4a 白底体系:splash 变体 = MobileLoginHandoffStage 唯一品牌宿主- expect(source).toContain(- "import { MobileLoginHandoffStage } from '@/components/MobileLoginHandoffStage';",- );- expect(source).toContain('<MobileLoginHandoffStage');- expect(source).toContain('testID="startup.splash"');- // 渲染层不再 require 任何旧 splash 资产(fade 立绘 / 白版字标 / script)- expect(source).not.toContain("require('../../assets/splash/");- // 旧资产文件暂留原目录(后续清理批次统一处置),仅校验存在性不校验消费- expect(- existsSync(resolve(process.cwd(), 'assets/splash/cindy-splash-illustration-fade.webp')),- ).toBe(true);- });-- it('keeps the branded splash free of app loading spinner, status text and red splash theme', () => {- const splashSource = readFileSync(resolve(process.cwd(), 'src/components/CenteredScreen.tsx'), 'utf8');- const stageSource = readFileSync(- resolve(process.cwd(), 'src/components/MobileLoginHandoffStage.tsx'),- 'utf8',- );- const layoutSource = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');- const indexSource = readFileSync(resolve(process.cwd(), 'app/index.tsx'), 'utf8');-- // splash 变体不带 loading spinner / 副标题状态文案(品牌纯净屏;- // ActivityIndicator 只存在于 default 变体分支)- expect(splashSource).toContain('if (variant === \'splash\') {');- expect(splashSource).not.toContain('colors.brandSplashMuted');- // 红底主题族不再被 splash 渲染链消费(白底体系 = 主题 surface + 双红渐变)- expect(splashSource).not.toContain('colors.brandSplashBackground');- expect(stageSource).not.toContain('brandSplash');- expect(stageSource).toContain('backgroundColor: colors.login.bgBase');- expect(layoutSource).not.toContain('subtitle="正在检查更新" variant="splash"');- expect(layoutSource).not.toContain('subtitle="正在启动" variant="splash"');- expect(indexSource).not.toContain('subtitle="正在恢复登录状态" variant="splash"');+// Unit: execute the production route. The dev-only preview must redirect when+// disabled; source/import/style assertions did not verify either route result.+describe('mobile splash preview route', () => {+ it.each([false, true])('gates the rendered preview when enabled=%s', (enabled) => {+ state.enabled = enabled;+ const element = SplashPreviewScreen();+ expect(element.type).toBe(enabled ? 'CenteredScreen' : 'Redirect');+ expect(element.props).toEqual(enabled ? { title: 'Cindy', variant: 'splash' } : { href: '/' });});});diff --git a/apps/mobile/src/__tests__/startupGateCopy.test.ts b/apps/mobile/src/__tests__/startupGateCopy.test.tsindex 5ab895d64f..2eabcba3e2 100644--- a/apps/mobile/src/__tests__/startupGateCopy.test.ts+++ b/apps/mobile/src/__tests__/startupGateCopy.test.ts@@ -1,82 +1,76 @@-import { readFileSync } from "node:fs";-import { resolve } from "node:path";-import { describe, expect, it, vi } from "vitest";+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import React from 'react';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';-/**- * 启动闸门文案 key 化状态测试(implementation-plan Step 1 v6.3 点名两处 / SC-4):- * ① endpoint 失败屏(app/_layout.tsx)错误态文案必须走 loginMessages key,- * 不得残留硬编码中文字符串字面量;- * ② config issue(src/config/env.ts)只产出 messageKey,由登录屏用 loginText 渲染。- * 组件树依赖 expo/RN 运行时,node vitest 下沿用仓内既有「读源码断言」模式;- * key → 5 语文案的桥接用 catalog 行为断言补齐。- */-vi.mock("expo-localization", () => ({- getLocales: () => [{ languageTag: "en-US" }],-}));+vi.mock('expo-localization', () => ({ getLocales: () => [{ languageTag: 'en-US' }] }));+import { loginMessages } from '@/auth/loginMessages';+import { getMobileConfigIssues } from '@/config/env';-import { loginMessages } from "@/auth/loginMessages";-import { getMobileConfigIssues } from "@/config/env";+// SC-4: execute the actual blocked-screen JSX and config-issue renderer. Catalog-only+// tests missed hardcoded rendered text and swapped reset/retry callbacks. No native app starts.+const layout = ts.createSourceFile('layout.tsx', readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const login = ts.createSourceFile('login.tsx', readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let blockedExpression: ts.Expression | undefined;+let configRenderer: ts.Expression | undefined;+function visitLayout(node: ts.Node) {+ if (ts.isIfStatement(node) && ts.isBinaryExpression(node.expression) && ts.isStringLiteral(node.expression.right) && node.expression.right.text === 'error') {+ const assignment = (child: ts.Node) => {+ if (ts.isBinaryExpression(child) && ts.isIdentifier(child.left) && child.left.text === 'body') blockedExpression ??= child.right;+ ts.forEachChild(child, assignment);+ };+ assignment(node.thenStatement);+ }+ ts.forEachChild(node, visitLayout);+}+function visitLogin(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === 'renderConfigIssues') configRenderer = node.initializer;+ ts.forEachChild(node, visitLogin);+}+visitLayout(layout); visitLogin(login);+if (!blockedExpression || !configRenderer) throw new Error('startup copy render entry missing');+const compilerOptions = { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 };+const blockedCode = ts.transpileModule(`const rendered = ${blockedExpression.getText(layout)};`, { compilerOptions }).outputText;+const configCode = ts.transpileModule(`const render = ${configRenderer.getText(login)}; const rendered = render();`, { compilerOptions }).outputText;-const layoutSource = readFileSync(- resolve(process.cwd(), "app/_layout.tsx"),- "utf8",-);-const envSource = readFileSync(- resolve(process.cwd(), "src/config/env.ts"),- "utf8",-);-const loginSource = readFileSync(- resolve(process.cwd(), "app/(auth)/login.tsx"),- "utf8",-);--describe("endpoint 闸门失败屏(_layout.tsx)文案 key 化", () => {- it("error 态文案与动态动作全部走 loginMessages key", () => {- expect(layoutSource).toContain("loginText('endpointGateTitle')");- expect(layoutSource).toContain("loginText('endpointGateSubtitle')");- expect(layoutSource).toContain("'endpointGateResetToDev' : 'retry'");- expect(layoutSource).toContain('endpointGate.resetToDev');- // {reason} 占位符在渲染点替换,保留闸门失败原因透出- expect(layoutSource).toContain("'{reason}'");- expect(layoutSource).toContain("endpointGate.reason ?? 'unknown'");- });-- it("旧硬编码中文字面量已清理", () => {- expect(layoutSource).not.toContain("无法获取服务器配置");- expect(layoutSource).not.toContain("请检查网络连接后重试");- expect(layoutSource).not.toContain('"重试"');+describe('startup gate localized rendering', () => {+ it.each([false, true])('renders the blocked reason and selects reset-to-dev=%s', (canResetToDev) => {+ const retry = vi.fn(); const resetToDev = vi.fn();+ const element = runInNewContext(`${blockedCode}+rendered`, {+ React, MobileLoginHandoffStage: 'brand', StartupGateBlockedContent: 'blocked',+ endpointGate: { canResetToDev, reason: 'offline fixture', retry, resetToDev },+ loginText: (key: keyof typeof loginMessages.en) => loginMessages.en[key],+ });+ const blocked = element.props.children;+ expect(blocked.type).toBe('blocked');+ expect(blocked.props.title).toBe(loginMessages.en.endpointGateTitle);+ expect(blocked.props.subtitle).toBe(loginMessages.en.endpointGateSubtitle.replace('{reason}', 'offline fixture'));+ expect(blocked.props.actionLabel).toBe(loginMessages.en[canResetToDev ? 'endpointGateResetToDev' : 'retry']);+ blocked.props.onAction();+ expect(retry).toHaveBeenCalledTimes(canResetToDev ? 0 : 1);+ expect(resetToDev).toHaveBeenCalledTimes(canResetToDev ? 1 : 0);});- it("闸门 key 在 5 语 catalog 全部就位", () => {- for (const locale of ["zh-CN", "zh-TW", "en", "ja", "ko"] as const) {+ it('renders invalid config through its message key for all five locales', () => {+ const configIssues = getMobileConfigIssues({ EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'ftp://auth.example.invalid' });+ expect(configIssues).toHaveLength(1);+ for (const locale of ['zh-CN', 'zh-TW', 'en', 'ja', 'ko'] as const) {const catalog = loginMessages[locale];- expect(catalog.endpointGateTitle.trim(), locale).not.toBe("");- expect(catalog.endpointGateSubtitle, locale).toContain("{reason}");- expect(catalog.endpointGateResetToDev.trim(), locale).not.toBe("");- expect(catalog.retry.trim(), locale).not.toBe("");- }- });-});--describe("config issue(env.ts)文案 key 化", () => {- it("issue 只产出 messageKey,旧裸文案已清理", () => {- expect(envSource).toContain("messageKey: 'configIssueAuthBaseUrl'");- expect(envSource).not.toContain("登录服务地址必须是");- });-- it("登录屏用 loginText 渲染 messageKey", () => {- expect(loginSource).toContain("loginText(issue.messageKey)");- expect(loginSource).not.toContain("issue.message}");- });-- it("行为桥接:非法 URL → messageKey → 5 语文案非空", () => {- const issues = getMobileConfigIssues({- EXPO_PUBLIC_CINDY_AUTH_BASE_URL: "ftp://auth.example.com",- });- expect(issues).toHaveLength(1);- const key = issues[0].messageKey;- for (const locale of ["zh-CN", "zh-TW", "en", "ja", "ko"] as const) {- expect(loginMessages[locale][key].trim(), locale).not.toBe("");+ const rendered = runInNewContext(`${configCode}+rendered`, {+ React, configIssues, LoginPanel: 'panel', LoginTitleBlock: 'title', View: 'view', Text: 'text',+ configIssueStyles: { list: {}, line: {} }, loginText: (key: keyof typeof catalog) => catalog[key],+ });+ const issueText = rendered.props.children[1].props.children[0];+ expect(issueText.props.children.join('')).toBe(`${configIssues[0].key}: ${catalog[configIssues[0].messageKey]}`);+ expect(catalog[configIssues[0].messageKey].trim(), locale).not.toBe('');+ expect(catalog.endpointGateTitle.trim(), locale).not.toBe('');+ expect(catalog.endpointGateSubtitle, locale).toContain('{reason}');+ expect(catalog.endpointGateResetToDev.trim(), locale).not.toBe('');+ expect(catalog.retry.trim(), locale).not.toBe('');}});-});+});\ No newline at end of filediff --git a/apps/mobile/src/__tests__/statusBarVcMigration.test.ts b/apps/mobile/src/__tests__/statusBarVcMigration.test.tsindex 3d83a2975f..a312659d7b 100644--- a/apps/mobile/src/__tests__/statusBarVcMigration.test.ts+++ b/apps/mobile/src/__tests__/statusBarVcMigration.test.ts@@ -77,3 +77,12 @@ describe('status bar VC-based migration source contracts', () => {);});});++// guard: DESIGN dual-mode delivery crosses the native router provider and stack surfaces.+it('wraps the native stack with the mode-aware navigation theme provider', () => {+ const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');++ expect(layout).toContain("mode === 'dark' ? NavigationDarkTheme : NavigationLightTheme");+ expect(layout).toContain('<NavigationThemeProvider value={navigationTheme}>');+ expect(layout).toContain('contentStyle: { backgroundColor: colors.surface }');+ });diff --git a/apps/mobile/src/__tests__/subagentRender.test.ts b/apps/mobile/src/__tests__/subagentRender.test.tsindex 1cf6b5e1c2..726c349674 100644--- a/apps/mobile/src/__tests__/subagentRender.test.ts+++ b/apps/mobile/src/__tests__/subagentRender.test.ts@@ -1,92 +1,101 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+// @vitest-environment jsdom+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CONTINUE_AFTER_ERROR_PROMPT } from '@cindy/maker-shared/synthetic-trigger';+import { i18n } from '@/i18n';+import { __test_internals as expansion } from '@/session/expandedBlockMemory';+import { collectMobileMessageGalleryImages } from '@/session/messageGallery';+import { normalizeRemoteMessages } from '@/session/messageNormalize';+import { buildMobileMessageRenderItems, type MobileSubagentGroupItem } from '@/session/messageRenderModel';+import type { RemoteMessage } from '@/session/types';+import { collaborationRenderer } from './fixtures/messageRendererComponents';-describe('subagent nesting render wiring', () => {- it('routes subagent_group items to a CollabCardShell-based SubagentCard (no new scroll mechanism)', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- // RenderItemView 新增 subagent_group 路由。- expect(source).toContain("case 'subagent_group':");- expect(source).toContain('<SubagentCard item={item} actions={actions} />');- // SubagentCard 走共享 CollabCardShell(其内部即 FoldablePanel,与 ToolGroupCard/WorkGroupCard 同款- // 折叠路径,未引入新滚动机制)、默认折叠。- const cardStart = source.indexOf('function SubagentCard(');- expect(cardStart).toBeGreaterThan(-1);- const cardEnd = source.indexOf('\nfunction FoldablePanel(', cardStart);- const cardSource = source.slice(cardStart, cardEnd);- expect(cardSource).toContain('<CollabCardShell');- // 展开态走 blockId 共享记忆(默认折叠),不再显式传 defaultExpanded(blockId 存在时该值无效)。- expect(cardSource).toContain('blockId={item.key}');- expect(cardSource).not.toContain('defaultExpanded');- expect(cardSource).toContain('testID="message.subagentToggle"');- // 递归渲染内层 childItems(经 RenderItemView)+ 子 agent 终稿。- expect(cardSource).toContain('item.childItems.map');- expect(cardSource).toContain('<RenderItemView');- expect(cardSource).toContain('item.summary');- // 颜色走主题 token(图标 textTertiary),不硬编码 hex。- expect(cardSource).toContain('colors.textTertiary');- expect(cardSource).not.toMatch(/#[0-9a-fA-F]{6}/);+const renderer = collaborationRenderer();+let root: Root;+let host: HTMLDivElement;+beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ await i18n.changeLanguage('en');+ expansion.reset();+ host = document.createElement('div');+ root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); vi.restoreAllMocks(); expansion.reset(); });+const message = (id: string, role: string, content: unknown, rest: Record<string, unknown> = {}): RemoteMessage => ({ id, clientId: id, role, content, sessionId: 'task', toolUseId: null, agentMeta: null, createdAt: '2026-01-01T00:00:00Z', ...rest } as RemoteMessage);+function group(key: string, childItems: MobileSubagentGroupItem['childItems'] = []): MobileSubagentGroupItem {+ return { type: 'subagent_group', key, header: { description: key, subagentType: 'research' }, childItems, summary: key + ' summary', status: 'running' };+}+function click(selector: string) {+ const button = host.querySelector<HTMLButtonElement>(selector);+ if (!button) throw new Error('Collaboration toggle was not found: ' + selector);+ act(() => button.click());+}++describe('subagent nesting render behavior', () => {+ it('dispatches nested subagents through collapsed cards, revealing children and summaries on demand', () => {+ const [normalized] = normalizeRemoteMessages([message('child', 'assistant', 'Nested response')]);+ const child = group('child-group', [{ type: 'message', key: 'leaf', message: normalized }]);+ act(() => root.render(createElement(renderer.RenderItemView, { item: group('parent-group', [child]), actions: { screenWidth: 320 } })));+ expect(host.querySelector('button')?.getAttribute('aria-expanded')).toBe('false');+ expect(host.textContent).not.toContain('parent-group summary');+ click('[data-testid="message.subagentToggle"]');+ expect(host.textContent).toContain('parent-group summary');+ expect(host.textContent).not.toContain('Nested response');+ const buttons = host.querySelectorAll<HTMLButtonElement>('[data-testid="message.subagentToggle"]');+ act(() => buttons[1].click());+ expect(host.textContent).toContain('Nested response');+ expect(host.textContent).toContain('child-group summary');});- it('guards both render-item dispatch points with an exhaustive log+skip default (compile-time exhaustiveness, no runtime throw)', () => {- const renderer = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const gallery = readFileSync(resolve(process.cwd(), 'src/session/messageGallery.ts'), 'utf8');- const helper = readFileSync(resolve(process.cwd(), 'src/session/assertNever.ts'), 'utf8');- // RenderItemView switch 与 messageGallery visitItem 都以 default: logUnhandledRenderItem(item) 收尾:- // 入参仍是 never → 给 union 加变体漏处理 → typecheck 拦下(保留 P3 编译期穷尽性);运行时 log+skip 不 throw- // (render/相册路径无 ErrorBoundary,不能崩整列)。- expect(helper).toContain('export function logUnhandledRenderItem(value: never): void');- expect(renderer).toContain("import { logUnhandledRenderItem } from '@/session/assertNever';");- expect(renderer).toContain('default:');- expect(renderer).toContain('logUnhandledRenderItem(item);');- expect(renderer).not.toContain('assertNever(item);'); // render 路径不再 throw- expect(gallery).toContain("import { logUnhandledRenderItem } from '@/session/assertNever';");- expect(gallery).toContain('logUnhandledRenderItem(item);');+ it('logs and skips unknown render variants in both the row and gallery without throwing', () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => undefined);+ const unknown = { type: 'future-variant', key: 'future' } as never;+ expect(() => act(() => root.render(createElement(renderer.RenderItemView, { item: unknown, actions: {} })))).not.toThrow();+ expect(host.textContent).toBe('');+ expect(collectMobileMessageGalleryImages([unknown])).toEqual([]);+ expect(log).toHaveBeenCalledTimes(2);+ expect(log.mock.calls.every(call => call[1] === unknown)).toBe(true);});- it('passes screenWidth into OrcaCollabCard and skips the foldable shell for empty body (F4 + F3)', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const orcaStart = source.indexOf('function OrcaCollabCard(');- const orcaSource = source.slice(orcaStart, source.indexOf('\nfunction ', orcaStart + 1));- // F4:OrcaCollabCard 收 screenWidth 并透传给 CollabCardShell。- expect(orcaSource).toContain('screenWidth?: number');- expect(orcaSource).toContain('screenWidth={screenWidth}');- // F3:body 为空 → 静态卡(无 CollabCardShell/chevron/空 body 区);有 body 才走折叠 shell。- expect(orcaSource).toContain("const body = card.body && card.body.trim() ? card.body : null;");- expect(orcaSource).toContain('if (!body) {');- expect(orcaSource).toContain('styles.orcaStaticHeader');+ it('uses a static Orca header for an empty body and responsive fold controls for a populated body', () => {+ act(() => root.render(createElement(renderer.OrcaCollabCard, { card: { variant: 'dispatch', title: 'Dispatch', body: ' ' }, screenWidth: 320, blockKey: 'empty' })));+ expect(host.textContent).toBe('Dispatch');+ expect(host.querySelector('button')).toBeNull();+ act(() => root.render(createElement(renderer.OrcaCollabCard, { card: { variant: 'dispatch', title: 'Dispatch', body: 'Body' }, screenWidth: 320, blockKey: 'body' })));+ const compact = host.querySelector('button')!.getAttribute('data-style');+ expect(host.textContent).not.toContain('Body');+ click('[data-testid="message.orcaCard.dispatch"]');+ expect(host.querySelector('[data-testid="message.orcaCardBody"]')?.textContent).toBe('Body');+ act(() => root.render(createElement(renderer.OrcaCollabCard, { card: { variant: 'dispatch', title: 'Dispatch', body: 'Body' }, screenWidth: 800, blockKey: 'body' })));+ expect(host.querySelector('button')!.getAttribute('data-style')).not.toBe(compact);});- it('shares one CollabCardShell chrome (FoldablePanel) between SubagentCard and OrcaCollabCard', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- // CollabCardShell 即 FoldablePanel(card 变体)+ Rail 的预设。- const shellStart = source.indexOf('function CollabCardShell(');- expect(shellStart).toBeGreaterThan(-1);- const shellSource = source.slice(shellStart, source.indexOf('\nfunction MobileSystemCard(', shellStart));- expect(shellSource).toContain('<FoldablePanel');- expect(shellSource).toContain("variant=\"card\"");- expect(shellSource).toContain('<Rail layout={layout}>');- // OrcaCollabCard 改用共享 chrome,数据路径仍是 card(message.orcaCard),且保留既有 testID。- const orcaStart = source.indexOf('function OrcaCollabCard(');- const orcaSource = source.slice(orcaStart, source.indexOf('\nfunction ', orcaStart + 1));- expect(orcaSource).toContain('<CollabCardShell');- expect(orcaSource).toContain('testID={`message.orcaCard.${card.variant}`}');- expect(orcaSource).toContain('testID="message.orcaCardBody"');- expect(orcaSource).not.toContain('styles.systemCard}'); // 不再用裸 systemCard 容器+ it('restores a manually expanded subagent after remounting the shared fold controls', () => {+ const item = group('remembered');+ const show = () => createElement(renderer.SubagentCard, { item, actions: { screenWidth: 402 } });+ act(() => root.render(show()));+ click('[data-testid="message.subagentToggle"]');+ expect(host.textContent).toContain('remembered summary');+ act(() => root.render(null));+ act(() => root.render(show()));+ expect(host.querySelector('button')?.getAttribute('aria-expanded')).toBe('true');+ expect(host.textContent).toContain('remembered summary');});- it('builds subagent_group via the parentUuid grouping path without touching shared builders', () => {- const model = readFileSync(resolve(process.cwd(), 'src/session/messageRenderModel.ts'), 'utf8');- // 无子 agent 时走原始 shared 路径(普通会话零影响),并把 live agent_task 更新接进 shared builder。- // 两条路径出口都套 dropSyntheticTriggerItems:合成续跑行不进渲染(隐藏 prompt 不露出)。- expect(model).toContain('if (!hasSubagentMessages(normalized))');- expect(model).toContain('return dropSyntheticTriggerItems(buildMessageRenderItems(normalized, options, taskUpdates));');- expect(model).toContain('buildSubagentAwareRenderItems(normalized, buildSubagentResultMeta(messages), options)');- // 联合类型扩为 mobile-only(shared 类型不动)。- expect(model).toContain("type: 'subagent_group';");- expect(model).toContain('| MobileSubagentGroupItem');- expect(model).toContain('| MobileForkOriginItem');- // 待发送气泡(pending_send)也是 mobile-only 的联合成员,同样不动 shared 类型。- expect(model).toContain('| MobilePendingSendItem;');+ it('groups actual parentUuid messages and keeps normal messages while hiding synthetic resume input', () => {+ const messages = [+ message('user', 'user', 'Start'),+ message('agent', 'tool_use', { toolName: 'Agent', toolUseId: 'agent-call', input: { description: 'Research' } }, { toolUseId: 'agent-call' }),+ message('child', 'assistant', 'Research result', { agentMeta: { parentUuid: 'agent-call' } }),+ message('result', 'tool_result', 'Research summary', { toolUseId: 'agent-call' }),+ message('resume', 'user', CONTINUE_AFTER_ERROR_PROMPT, { agentMeta: { autoResume: true } }),+ ];+ const items = buildMobileMessageRenderItems(messages, {});+ const nested = items.find(item => item.type === 'subagent_group');+ expect(nested).toMatchObject({ type: 'subagent_group', summary: 'Research summary' });+ expect(items.some(item => item.type === 'message' && item.message.body === 'Start')).toBe(true);+ expect(items.some(item => item.type === 'message' && item.message.body === CONTINUE_AFTER_ERROR_PROMPT)).toBe(false);+ expect(nested?.type === 'subagent_group' && nested.childItems.length).toBeGreaterThan(0);});});diff --git a/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.tsindex b77ded1528..8afce710cd 100644--- a/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts+++ b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts@@ -1,39 +1,121 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+// @vitest-environment jsdom+import { act, createElement, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SwipeableSessionRow } from '@/session/SwipeableSessionRow';+import type { RemoteSession } from '@/session/types';-const source = readFileSync(- resolve(process.cwd(), 'src/session/SwipeableSessionRow.tsx'),- 'utf8',-);--describe('SwipeableSessionRow native animation lifecycle', () => {- it('uses the classic RNGH Swipeable instead of Reanimated synchronous UI props', () => {- expect(source).toContain('ClassicSwipeable as Swipeable');- expect(source).not.toContain('ReanimatedSwipeable as Swipeable');- expect(source).not.toContain("from 'react-native-reanimated'");- });+const runtime = vi.hoisted(() => ({+ props: null as any, release: 0, translation: null as any,+ listeners: new Map<string, (event: { value: number }) => void>(),+ removed: vi.fn(), stopped: vi.fn(), close: vi.fn(), reset: vi.fn(),+}));+vi.mock('react-native', async () => {+ const { createElement: el } = await import('react');+ const View = ({ children }: { children?: ReactNode }) => el('div', null, children);+ class Value {+ setValue() {}+ stopAnimation() { runtime.stopped(); }+ interpolate() { return this; }+ }+ const node = { interpolate: () => node };+ return {+ View, Pressable: ({ children, testID }: any) => el('button', { 'data-testid': testID }, children),+ StyleSheet: { create: (value: unknown) => value }, useWindowDimensions: () => ({ width: 400 }),+ Animated: { Value, View, add: () => node, divide: () => node, multiply: () => node,+ subtract: () => node, timing: () => ({ start() {} }) },+ };+});+vi.mock('@/platform/gestureHandler', async () => {+ const { createElement: el, Fragment, forwardRef, useImperativeHandle } = await import('react');+ runtime.translation = {+ __getValue: () => runtime.release,+ interpolate: () => runtime.translation,+ addListener: (callback: (event: { value: number }) => void) => {+ const id = String(runtime.listeners.size + 1);+ runtime.listeners.set(id, callback);+ return id;+ },+ removeListener: (id: string) => { runtime.removed(id); runtime.listeners.delete(id); },+ };+ return { ClassicSwipeable: forwardRef((props: any, ref) => {+ runtime.props = props;+ useImperativeHandle(ref, () => ({ close: runtime.close, reset: runtime.reset }));+ return el(Fragment, null, props.renderLeftActions({}, runtime.translation),+ props.renderRightActions({}, runtime.translation), props.children);+ }) };+});+vi.mock('lucide-react-native', () => Object.fromEntries(+ ['Archive', 'ArchiveRestore', 'Ellipsis', 'Pin', 'PinOff'].map((name) => [name, () => null]),+));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/session/listDisclosureTransition', () => ({ useDisclosurePrepare: () => () => {} }));+vi.mock('@/session/swipeRowRegistry', () => ({+ pinToggleAction: () => ({ label: 'pin' }), statusToggleAction: () => ({ label: 'archive', action: 'archive' }),+}));+vi.mock('@/theme', () => ({+ iconSize: { swipeAction: 24 }, iconStroke: { regular: 2 },+ useTheme: () => ({ colors: {} }), useThemedStyles: (make: (colors: object) => unknown) => make({}),+}));+vi.mock('@/theme/tokens', () => ({ radius: { pill: 9999 }, spacing: { md: 12 } }));- it('reads the release position instead of a peak and disposes Animated listeners', () => {- expect(source).toContain('const value = translationRef.current?.__getValue?.();');- expect(source).toContain('const releaseTranslation = readReleaseTranslation();');- expect(source).not.toContain('peakTranslationRef');- expect(source).toContain('translation.removeListener(listenerId)');- expect(source).toContain('armedProgress.stopAnimation();');- });+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: Root;+let host: HTMLDivElement;+const controls = {+ onArchive: vi.fn(), onTogglePin: vi.fn(), onShowOptions: vi.fn(),+ registry: { onRowOpen: vi.fn(), onRowClose: vi.fn(), closeOpenRow: vi.fn() },+};+function render(id = 'row') {+ act(() => root.render(createElement(SwipeableSessionRow, {+ ...controls, session: { id, status: 'active' } as RemoteSession, testID: 'swipe', children: 'row',+ })));+}+beforeEach(() => {+ vi.clearAllMocks(); runtime.release = 0; runtime.listeners.clear();+ host = document.createElement('div'); root = createRoot(host);+});+afterEach(() => act(() => root.unmount()));- it('keeps only fixed action shells mounted until a swipe starts', () => {- expect(source).toContain('const [mountedActionRowKey, setMountedActionRowKey] = useState<string | null>(null);');- expect(source).toContain('const actionsMounted = mountedActionRowKey === rowKey;');- expect(source).toContain('setMountedActionRowKey(rowKey);');- expect(source).toContain('setMountedActionRowKey(null);');- expect(source).toContain('{actionsMounted ? (');- expect(source).toContain('<View style={styles.pinShell}>');- expect(source).toContain('<View style={styles.rightShell}>');+// Unit: render the production classic row at a mocked native boundary. These+// regressions protect release-position archiving, lazy native trees and disposal;+// the old import/substring/layout checks never invoked a gesture or React cleanup.+describe('classic swipe row lifecycle', () => {+ it.each([+ ['right', -260, -100, false, 'onArchive'],+ ['right', -260, -260, true, 'onArchive'],+ ['left', 260, 100, false, 'onTogglePin'],+ ['left', 260, 260, true, 'onTogglePin'],+ ] as const)('uses release position for %s after peak=%s, end=%s', (direction, peak, end, fires, action) => {+ render();+ expect(runtime.listeners.size).toBe(0);+ expect(host.querySelector('button')).toBeNull();+ act(() => runtime.props.onSwipeableOpenStartDrag());+ expect(runtime.listeners.size).toBe(2);+ expect(host.querySelectorAll('button')).toHaveLength(3);+ act(() => {+ for (const listener of runtime.listeners.values()) listener({ value: peak });+ runtime.release = end;+ runtime.props.onSwipeableWillOpen(direction);+ });+ expect(controls[action]).toHaveBeenCalledTimes(fires ? 1 : 0);+ if (fires) expect(controls[action]).toHaveBeenCalledWith(expect.objectContaining({ id: 'row' }));+ const stoppedBefore = runtime.stopped.mock.calls.length;+ act(() => runtime.props.onSwipeableClose());+ expect(runtime.listeners.size).toBe(0);+ expect(runtime.removed).toHaveBeenCalledTimes(2);+ expect(runtime.stopped.mock.calls.length).toBeGreaterThan(stoppedBefore);+ expect(host.querySelector('button')).toBeNull();});- it('keeps the two right-side action buttons evenly spaced', () => {- expect(source).toMatch(/optionsButton:\s*\{[\s\S]*?right: BUTTON_GAP \* 2 \+ BUTTON_SIZE,/);- expect(source).toMatch(/archiveButton:\s*\{[\s\S]*?right: BUTTON_GAP,/);+ it('retires listeners and armed animation when a visible row unmounts', () => {+ render();+ act(() => runtime.props.onSwipeableOpenStartDrag());+ const stoppedBefore = runtime.stopped.mock.calls.length;+ act(() => root.render(null));+ expect(runtime.listeners.size).toBe(0);+ expect(runtime.removed).toHaveBeenCalledTimes(2);+ expect(runtime.stopped.mock.calls.length).toBeGreaterThan(stoppedBefore);+ expect(controls.registry.onRowClose).toHaveBeenCalledWith('row');});-});+});\ No newline at end of filediff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsxindex f7fc878a88..4123499cca 100644--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx@@ -374,7 +374,7 @@ it.each(['/context', '/learn keep this', '/help', 'keep this message'])('preservts.forEachChild(node, visit);};visit(screen);- expect(guard).toBeDefined();+ if (!guard) throw new Error('Missing production remote-command guard');const error = vi.fn();const consume = vi.fn();const run = new Function('args', `diff --git a/apps/mobile/src/__tests__/userMessageCollapse.test.ts b/apps/mobile/src/__tests__/userMessageCollapse.test.tsindex 19fc1921da..5c77367f6a 100644--- a/apps/mobile/src/__tests__/userMessageCollapse.test.ts+++ b/apps/mobile/src/__tests__/userMessageCollapse.test.ts@@ -1,6 +1,13 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+// @vitest-environment jsdom+import * as React from 'react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { i18n } from '@/i18n';+import { buildMessageContentLayout, nextSettledContentWidth } from '@/session/messageContentLayout';+import { selectableTextVerticalOffset } from '@/session/selectableTextAlignment';+import { rendererFunction, rendererSource, executeRenderer } from './fixtures/messageRendererComponents';import { PR_WATCH_EXPANDED_BLANK_FIXTURE } from '@/__tests__/fixtures/prWatchExpandedBlank';import {@@ -133,46 +140,149 @@ describe('truncateTextToVisualLines', () => {});});-describe('MessageRenderer 长消息测量接线', () => {- it('caps the invisible native text layout at one line past the collapse threshold', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const measureStart = source.indexOf('{collapseMeasureEnabled ? (');- const measureEnd = source.indexOf('{shouldCollapseLongMessage ? (', measureStart);+// Regression: PR-watch Markdown used to mount a giant iOS UITextView after+// expansion, causing blank content. Execute the existing collapse hooks/bubble+// and MarkdownBody callbacks; only native surfaces and inline formatting adapt.+function bodyStatement(name: string, functionName: string): ts.Statement {+ const statement = rendererFunction(functionName).body!.statements.find(candidate =>+ ts.isVariableStatement(candidate) && candidate.declarationList.declarations.some(declaration => {+ const names = ts.isIdentifier(declaration.name) ? [declaration.name.text]+ : ts.isArrayBindingPattern(declaration.name) ? declaration.name.elements.flatMap(element => ts.isBindingElement(element) && ts.isIdentifier(element.name) ? [element.name.text] : []) : [];+ return names.includes(name);+ }));+ if (!statement) throw new Error('Renderer state declaration was not found: ' + name);+ return statement;+}+const bubbleStatements = rendererFunction('MessageBubble').body!.statements;+const collapseStart = bubbleStatements.indexOf(bodyStatement('automationOrigin', 'MessageBubble'));+const collapseEnd = bubbleStatements.indexOf(bodyStatement('longMessageCollapsed', 'MessageBubble'));+const collapseCode = bubbleStatements.slice(collapseStart, collapseEnd + 1).map(statement => statement.getText(rendererSource)).join(String.fromCharCode(10));+const markdownStateCode = ['contentWidth', 'handleSettledWidthLayout', 'pinSettledWidth', 'settledTextStyle', 'renderSingleBlock']+ .map(name => bodyStatement(name, 'MarkdownBody').getText(rendererSource)).join(String.fromCharCode(10));+const markdownReturn = rendererFunction('MarkdownBody').body!.statements.find(ts.isReturnStatement);+if (!markdownReturn) throw new Error('MarkdownBody return was not found');- expect(measureStart).toBeGreaterThan(-1);- expect(measureEnd).toBeGreaterThan(measureStart);- expect(source.slice(measureStart, measureEnd)).toContain(- 'numberOfLines={collapseThreshold + 1}',- );+let root: Root;+let host: HTMLDivElement;+const nativeLayouts = new Map<string, (event: unknown) => void>();+const nativeTextLayouts = new Map<string, (event: unknown) => void>();+type SurfaceProps = { children?: React.ReactNode; testID?: string; style?: unknown; onPress?: () => void; onLayout?: (event: unknown) => void; onTextLayout?: (event: unknown) => void; numberOfLines?: number; accessibilityElementsHidden?: boolean };+function NativeView(props: SurfaceProps) {+ if (props.onLayout) nativeLayouts.set(props.testID ?? 'anonymous', props.onLayout);+ return React.createElement('div', { 'data-testid': props.testID, 'data-hidden': props.accessibilityElementsHidden, 'data-style': JSON.stringify(props.style) }, props.children);+}+function nativeText(surface: string) {+ return (props: SurfaceProps) => {+ if (props.onTextLayout) nativeTextLayouts.set(props.testID ?? 'measure', props.onTextLayout);+ return React.createElement(props.onPress ? 'button' : 'span', {+ 'data-testid': props.testID, 'data-surface': surface, 'data-max-lines': props.numberOfLines,+ 'data-style': JSON.stringify(props.style), onClick: props.onPress,+ }, props.children);+ };+}+const Text = nativeText('rn-text');+const UITextView = nativeText('ios-text-view');+const ScrollView = (props: SurfaceProps) => React.createElement('div', { 'data-scroll': true }, props.children);+const { BubbleHarness, MarkdownHarness } = executeRenderer<{ BubbleHarness: React.ComponentType<any>; MarkdownHarness: React.ComponentType<any> }>(+ rendererFunction('MarkdownSelectableText').getText(rendererSource) + String.raw`+function MarkdownHarness({ pinContentWidth = false, allowIosUITextView = true, selectable, text, layout, code = false }) {+ const styles = {};+ const onOpenPayload = undefined;+ const inlinesSelectable = () => true;+ const spanFor = () => undefined;+ const renderInlines = inlines => inlines.map(inline => inline.text).join('');+ const t = i18n.t.bind(i18n);+ ` + markdownStateCode + String.raw`+ const groups = [{ type: 'block', key: 'body', block: code+ ? { type: 'code', key: 'code', text, language: 'text' }+ : { type: 'paragraph', key: 'paragraph', inlines: [{ type: 'text', text }] } }];+ ` + markdownReturn.getText(rendererSource) + String.raw`+}+const MarkdownBody = MarkdownHarness;+function BubbleHarness({ body, kind = 'user', automationOrigin: origin }) {+ const styles = {};+ const isUser = kind === 'user';+ const item = { message: { kind, body, automationOrigin: origin } };+ const displayBubbleBody = body;+ const bubbleBody = body;+ const hasPluginInvocations = false;+ const userBubbleColors = undefined;+ const actions = {};+ const colors = {};+ const presentation = {};+ const rendersSentInlineBody = false;+ const canSelectVisibleText = true;+ const isStreamingAssistant = false;+ const contentLayout = buildMessageContentLayout({ screenWidth: 402 });+ const t = i18n.t.bind(i18n);+ ` + collapseCode + bodyStatement('bubble', 'MessageBubble').getText(rendererSource) + String.raw`+ return bubble;+}+return { BubbleHarness, MarkdownHarness };+`, {+ useContext: React.useContext, useRef: React.useRef, useMemo: React.useMemo,+ useEffect: React.useEffect, useCallback: React.useCallback, useRecyclingState: React.useState,+ SelectionQuoteContext: React.createContext(null), useWindowDimensions: () => ({ fontScale: 1 }),+ Platform: { OS: 'ios' }, StyleSheet: { flatten: (style: unknown) => style },+ selectableTextVerticalOffset, MAX_FONT_SIZE_MULTIPLIER: 2, i18n,+ View: NativeView, Text, UITextView, ScrollView,+ buildMessageContentLayout, nextSettledContentWidth,+ MarkdownBlockContent: ({ block, renderBlock }: { block: unknown; renderBlock: (block: unknown) => React.ReactNode }) => renderBlock(block),+ HighlightedCodeText: ({ text }: { text: string }) => React.createElement('code', null, text),+ mayExceedVisualLineThreshold, resolveUserMessageCollapse,+ AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD, AUTOMATION_USER_MESSAGE_COLLAPSED_LINES,+ LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD, LONG_USER_MESSAGE_COLLAPSED_LINES,+ });++describe('MessageRenderer bounded long-message native behavior', () => {+ beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ await i18n.changeLanguage('en');+ host = document.createElement('div');+ root = createRoot(host);+ nativeLayouts.clear();+ nativeTextLayouts.clear();+ });+ afterEach(() => act(() => root.unmount()));++ it('bounds hidden native measurement and keeps the message collapsible after its capped layout reply', () => {+ act(() => root.render(React.createElement(BubbleHarness, { body: PR_WATCH_EXPANDED_BLANK_FIXTURE })));+ const measure = host.querySelector('[data-hidden="true"] [data-max-lines]');+ expect(measure?.getAttribute('data-max-lines')).toBe(String(LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD + 1));+ act(() => nativeTextLayouts.get('measure')!({ nativeEvent: { lines: Array.from({ length: Number(measure!.getAttribute('data-max-lines')) }, () => ({ text: 'line' })) } }));+ expect(host.querySelector('[data-testid="message.collapsedBody"]')).not.toBeNull();+ expect(host.querySelector('[data-testid="message.collapseToggle"]')).not.toBeNull();+ // Automation inputs use the actual tighter threshold, including their native cap.+ act(() => root.render(React.createElement(BubbleHarness, { body: PR_WATCH_EXPANDED_BLANK_FIXTURE, automationOrigin: { kind: 'schedule' } })));+ expect(host.querySelector('[data-hidden="true"] [data-max-lines]')?.getAttribute('data-max-lines'))+ .toBe(String(AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD + 1));+ });++ it('uses RN Text for expanded long iOS messages while ordinary selectable messages keep UITextView', () => {+ act(() => root.render(React.createElement(BubbleHarness, { body: 'A short message' })));+ expect(host.querySelector('[data-testid="message.markdownBody"] [data-surface]')?.getAttribute('data-surface')).toBe('ios-text-view');+ act(() => root.render(React.createElement(BubbleHarness, { body: PR_WATCH_EXPANDED_BLANK_FIXTURE })));+ expect(host.querySelector('[data-testid="message.collapsedBody"]')?.getAttribute('data-surface')).toBe('ios-text-view');+ act(() => host.querySelector<HTMLButtonElement>('[data-testid="message.collapseToggle"]')!.click());+ expect(host.querySelector('[data-testid="message.markdownBody"] [data-surface]')?.getAttribute('data-surface')).toBe('rn-text');+ expect(host.querySelector('[data-testid="message.markdownBody"]')?.textContent).toBe(PR_WATCH_EXPANDED_BLANK_FIXTURE);});- it('falls back from the giant iOS UITextView only after a long message is expanded', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const bubbleStart = source.indexOf('function MessageBubble');- const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);- const bubbleSource = source.slice(bubbleStart, bubbleEnd);-- expect(bubbleSource).toContain('allowIosUITextView={!shouldCollapseLongMessage}');- expect(source).toContain('if (selectable && allowIosUITextView && Platform.OS === \'ios\')');- });-- it('keeps expanded user markdown hugging the bubble instead of pinning list width', () => {- const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');- const bubbleStart = source.indexOf('function MessageBubble');- const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);- const bubbleSource = source.slice(bubbleStart, bubbleEnd);- const markdownBodyStart = source.indexOf('function MarkdownBody');- const markdownBodyEnd = source.indexOf('function ChatPathChipSpan', markdownBodyStart);- const markdownBodySource = source.slice(markdownBodyStart, markdownBodyEnd);-- expect(bubbleSource).toContain('pinContentWidth={!isUser}');- expect(markdownBodySource).toContain('if (!pinContentWidth) return;');- const codeStart = markdownBodySource.indexOf("if (block.type === 'code')");- const headingStart = markdownBodySource.indexOf("if (block.type === 'heading')", codeStart);- const codeSource = markdownBodySource.slice(codeStart, headingStart);- expect(codeStart).toBeGreaterThan(-1);- expect(headingStart).toBeGreaterThan(codeStart);- expect(codeSource).not.toContain('<ScrollView');- expect(codeSource).toContain('围栏代码在气泡内换行');+ it('keeps user markdown at its content width and wraps fenced code without a nested scroll host', () => {+ const body = PR_WATCH_EXPANDED_BLANK_FIXTURE;+ act(() => root.render(React.createElement(BubbleHarness, { body })));+ act(() => host.querySelector<HTMLButtonElement>('[data-testid="message.collapseToggle"]')!.click());+ const markdown = () => host.querySelector('[data-testid="message.markdownBody"]')!;+ const before = markdown().getAttribute('data-style');+ act(() => nativeLayouts.get('message.markdownBody')!({ nativeEvent: { layout: { width: 402 } } }));+ expect(markdown().getAttribute('data-style')).toBe(before);+ expect(markdown().firstElementChild?.getAttribute('data-style')).toBe('null');+ act(() => root.render(React.createElement(MarkdownHarness, { text: 'agent', selectable: true, pinContentWidth: true, layout: buildMessageContentLayout({ screenWidth: 402 }) })));+ act(() => nativeLayouts.get('message.markdownBody')!({ nativeEvent: { layout: { width: 402 } } }));+ expect(JSON.parse(markdown().firstElementChild!.getAttribute('data-style')!)).toMatchObject({ width: 402 });+ const code = 'code '.repeat(200);+ act(() => root.render(React.createElement(MarkdownHarness, { text: code, code: true, layout: buildMessageContentLayout({ screenWidth: 402 }) })));+ expect(host.querySelector('code')?.textContent).toBe(code);+ expect(host.querySelector('[data-scroll]')).toBeNull();});});diff --git a/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts b/apps/mobile/src/auth/__tests__/loginCaptcha.test.tsindex 9687d228f3..7bc0a730f6 100644--- a/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts+++ b/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import { parseCaptchaWebViewMessage } from '@/auth/loginCaptchaMessage';@@ -154,129 +152,3 @@ describe('mobile captcha WebView 导航与消息契约边界', () => {).toBe(false);});});--describe('AuthContext captcha 闸接线(静态源码断言)', () => {- const authContextSource = readFileSync(- resolve(process.cwd(), 'src/auth/AuthContext.tsx'),- 'utf8',- );- const loginSource = readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8');- const captchaWebViewSource = readFileSync(- resolve(process.cwd(), 'src/auth/LoginCaptchaWebView.tsx'),- 'utf8',- );-- it('discover 的 sole email_code 自动串发路径先过 ensureCaptchaGate', () => {- const soleBranch = authContextSource.slice(- authContextSource.indexOf("sole?.type === 'email_code'"),- authContextSource.indexOf("updateLoginState(\n reduceAuthFlow(currentState, {\n type: 'code-requested'"),- );- expect(soleBranch).toContain("ensureCaptchaGate('email')");- expect(soleBranch).toContain('requestCodeWithCaptchaFallback');- });-- it('request-code 的 email/phone 都按 requiredFor 动作过闸,取消不派发', () => {- const branch = authContextSource.slice(- authContextSource.indexOf("if (action.type === 'request-code')"),- authContextSource.indexOf("if (action.type === 'verify-code')"),- );- expect(branch).toContain('ensureCaptchaGate(action.kind)');- expect(branch).toContain('if (!gate.proceed) return false;');- expect(branch).toContain('requestCodeWithCaptchaFallback');- expect(authContextSource).toContain('captchaRequiredActionForVerificationKind(kind)');- expect(authContextSource).toContain('?action=${encodeURIComponent(action)}&lang=');- });-- it('挑战页地址由构建区域 authApiBaseUrl + 共享路径常量拼出', () => {- expect(authContextSource).toContain('CAPTCHA_CHALLENGE_PAGE_PATH');- expect(authContextSource).toContain(- "getMobileEndpointForRealm(BUILD_AUTH_REGION, 'authApiBaseUrl')",- );- });-- it('显示 captcha WebView 前先收起软键盘', () => {- const challengeBranch = authContextSource.slice(- authContextSource.indexOf('const runCaptchaChallenge'),- authContextSource.indexOf('const ensureCaptchaGate'),- );- expect(authContextSource).toMatch(- /import \{[^}]*\bKeyboard\b[^}]*\} from 'react-native';/,- );- expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeGreaterThan(-1);- expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeLessThan(- challengeBranch.indexOf('setCaptchaChallenge({ url });'),- );- });-- it('login.tsx 渲染 captcha WebView 模态并接回 resolveCaptchaChallenge', () => {- expect(loginSource).toContain('auth.captchaChallenge');- expect(loginSource).toContain('LoginCaptchaWebView');- expect(loginSource).toContain('auth.resolveCaptchaChallenge');- });-- it('captcha WebView 限制导航但不把客户端消息来源当作认证边界', () => {- expect(captchaWebViewSource).toContain("originWhitelist={['*']}");- expect(captchaWebViewSource).toContain('setSupportMultipleWindows={false}');- expect(captchaWebViewSource).toContain('isAllowedLoginCaptchaNavigation(request, themedUrl)');- expect(captchaWebViewSource).not.toContain('event.nativeEvent.url');- expect(captchaWebViewSource).not.toMatch(/^\s*incognito(?:\s|=)/m);- expect(captchaWebViewSource).toContain(- 'parseCaptchaWebViewMessage(event.nativeEvent.data)',- );- expect(captchaWebViewSource).not.toContain('`${pageOrigin}/*`');- });-- it('captcha WebView 使用 ThemeOverrideProvider 内的有效登录主题', () => {- expect(captchaWebViewSource).toContain('const { colors, mode } = useTheme()');- expect(captchaWebViewSource).toContain('withLoginCaptchaTheme(url, mode)');- expect(captchaWebViewSource).toContain('source={{ uri: themedUrl }}');- });-- it('captcha WebView 的 iOS/Android 渲染进程异常都进入失败重试态', () => {- expect(captchaWebViewSource).toContain('onContentProcessDidTerminate={() => setFailed(true)}');- expect(captchaWebViewSource).toContain('onRenderProcessGone={() => setFailed(true)}');- });-- it('captcha WebView 超时后进入重试态,并在完成、重试或卸载时清理计时器', () => {- expect(captchaWebViewSource).toContain('const CHALLENGE_TIMEOUT_MS = 120_000;');- expect(captchaWebViewSource).toContain('const timeoutTimer = setTimeout(() => {');- expect(captchaWebViewSource).toContain('return () => clearTimeout(timeoutTimer);');- expect(captchaWebViewSource).toContain('}, [failed, generation, themedUrl]);');- });-- it('captcha 重试与取消动作都提供至少 44×44 的触控目标', () => {- for (const testId of ['login.captcha.retry', 'login.captcha.cancel']) {- const marker = `testID="${testId}"`;- const nativeMarkerIndex = captchaWebViewSource.indexOf(marker);- const nativeStart = captchaWebViewSource.lastIndexOf('<LoginNativeButton', nativeMarkerIndex);- expect(nativeStart).toBeGreaterThan(-1);- expect(captchaWebViewSource.slice(nativeStart, nativeMarkerIndex)).toContain('height={44}');- const markerIndex = captchaWebViewSource.lastIndexOf(marker);- const actionStart = captchaWebViewSource.lastIndexOf('<Pressable', markerIndex);- const actionSource = captchaWebViewSource.slice(actionStart, markerIndex);- expect(markerIndex).toBeGreaterThan(-1);- expect(actionStart).toBeGreaterThan(-1);- expect(actionSource).toContain('minHeight: 44');- expect(actionSource).toContain('minWidth: 44');- }- });-- it('captcha 卡片和挑战内容在窄屏内按安全边距收缩', () => {- expect(captchaWebViewSource).toContain('paddingHorizontal: spacing.lg');- expect(captchaWebViewSource).toContain('maxWidth: 340');- expect(captchaWebViewSource).toContain("width: '100%'");- expect(captchaWebViewSource.match(/alignSelf: 'stretch'/g)).toHaveLength(2);- expect(captchaWebViewSource).not.toContain('width: 340');- expect(captchaWebViewSource).not.toContain('width: 308');- });-- it('captcha 打开时从 Android TalkBack 隐藏背景登录组与注销气泡', () => {- expect(loginSource).toContain('const captchaChallengeOpen = auth.captchaChallenge !== null');- expect(loginSource).toContain(- 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen || handoffPhase',- );- expect(loginSource).toContain(- 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen',- );- });-});diff --git a/apps/mobile/src/auth/__tests__/loginConsent.test.ts b/apps/mobile/src/auth/__tests__/loginConsent.test.tsindex f6565d1bd8..70afb9f80d 100644--- a/apps/mobile/src/auth/__tests__/loginConsent.test.ts+++ b/apps/mobile/src/auth/__tests__/loginConsent.test.ts@@ -1,6 +1,8 @@import { readFileSync } from "node:fs";import { resolve } from "node:path";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";+import * as React from "react";+import ts from "typescript";import { parseLegalSegments } from "@/auth/legalText";import { LOGIN_CONSENT_ROW } from "@/auth/loginSkinLayout";@@ -8,6 +10,39 @@ import { LEGAL_LINKS } from "@/config/legalLinks";import { loginPalettes } from "@/theme/tokens";import { loginMessages } from "@/auth/loginMessages";+it('evaluates the production regional legal links for the Global build', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/config/legalLinks.ts'), 'utf8');+ const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;+ const exports: any = {};+ new Function('require', 'exports', compiled)(() => ({ AUTH_REGION: 'global' }), exports);+ expect(exports.LEGAL_LINKS).toEqual({ termsOfService: 'https://protocol.xd.com/cindy/agreement-1.0.html', privacyPolicy: 'https://protocol.xd.com/cindy/privacy.html' });+});++// The P1 was clipped Android hit bounds and an unlabeled checkbox. Run the+// production component, checking actual hit geometry and accessible properties.+it.each(['light', 'dark'] as const)('keeps consent reachable, labeled and interactive in %s mode', (mode) => {+ const source = ts.createSourceFile('controls.tsx', readFileSync(resolve(process.cwd(), 'src/components/LoginSkinControls.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const row = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'LoginConsentRow');+ if (!row) throw new Error('Missing production consent row');+ const code = ts.transpileModule(row.getText(source).replace(/^export\s+/, ''), { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+ const bindings = { React, View: 'View', Pressable: 'Pressable', ConsentCheckGlyph: 'Check', LegalStatementText: 'LegalText',+ useTheme: () => ({ colors: { login: loginPalettes[mode] } }), LOGIN_CONSENT_ROW, parseLegalSegments };+ const render = new Function(...Object.keys(bindings), code + '\nreturn LoginConsentRow;')(...Object.values(bindings));+ const toggle = vi.fn();+ const tree = render({ checked: true, onToggle: toggle, statement: loginMessages.en.consentStatement, onOpenTerms: vi.fn(), onOpenPrivacy: vi.fn() });+ const radio = tree.props.children[0];+ expect(radio.props.accessibilityRole).toBe('checkbox');+ expect(radio.props.accessibilityState).toEqual({ checked: true });+ expect(radio.props.accessibilityLabel).not.toMatch(/[<>]/);+ expect(radio.props.style.height).toBeGreaterThanOrEqual(88);+ expect(radio.props.style.width).toBeGreaterThanOrEqual(88);+ expect(radio.props.hitSlop).toBeUndefined();+ expect(tree.props.style.top + tree.props.style.height).toBe(LOGIN_CONSENT_ROW.y + LOGIN_CONSENT_ROW.height);+ radio.props.onPress();+ expect(toggle).toHaveBeenCalledOnce();+ expect(radio.props.children.props.style.backgroundColor).toBe(loginPalettes[mode].consentRadioCheckedBg);+});+/*** 协议同意链路专测(consent PR,移动端):* 组件树依赖 expo/RN 运行时,node vitest 下沿用仓内「纯数据断言 + 读源码接线断言」@@ -15,14 +50,6 @@ import { loginMessages } from "@/auth/loginMessages";* LoginPage.consent.test.tsx 同源(桌面 jsdom 全交互覆盖)。*/-const loginSource = readFileSync(- resolve(process.cwd(), "app/(auth)/login.tsx"),- "utf8",-);-const controlsSource = readFileSync(- resolve(process.cwd(), "src/components/LoginSkinControls.tsx"),- "utf8",-);describe("parseLegalSegments(单 key 内联链接标记,词序无关)", () => {it("zh 语序:前缀文本 + terms/privacy 链接段 + 连接词", () => {@@ -67,18 +94,6 @@ describe("LEGAL_LINKS(区域分流,测试构建 = cn)", () => {"https://protocol.xd.cn/cindy/privacy-1.0.html",);});-- it("global 分支 URL 固化在源码(protocol.xd.com 双链接)", () => {- const source = readFileSync(- resolve(process.cwd(), "src/config/legalLinks.ts"),- "utf8",- );- expect(source).toContain(- "https://protocol.xd.com/cindy/agreement-1.0.html",- );- expect(source).toContain("https://protocol.xd.com/cindy/privacy.html");- expect(source).toContain("AUTH_REGION === 'global'");- });});describe("consent 双态色板(figma wave5 SVG 源码核对值,与桌面 --login-consent-* 同源)", () => {@@ -150,73 +165,6 @@ describe("consent 文案(5 语 catalog 全给标记链接段)", () => {);});-describe("login.tsx 接线(源码断言)", () => {- it("个人链路发起点全部过 requireConsent,含 email discover(产品拍板 2026-07-24 二次)", () => {- const guarded = loginSource.match(/requireConsent\(/g) ?? [];- // 调用点 ≥5 处(email discover/phone 发码/邮箱个人行发码/apple/nonApple)- expect(guarded.length).toBeGreaterThanOrEqual(5);- // 手机号/邮箱提交一律先弹协议弹窗(拍板压过审查侧「discover 纯查询可放行」建议)- expect(loginSource).toMatch(- /requireConsent\(\(\) =>[\s\S]{0,140}?type: 'discover'/,- );- // 发码点(phone + 邮箱个人行)与社交圆钮为实际发起点,必须过门- expect(loginSource).toMatch(- /requireConsent\(\(\) =>[\s\S]{0,200}?kind: 'phone'/,- );- expect(loginSource).toMatch(- /requireConsent\(\(\) =>[\s\S]{0,240}?kind: 'email'/,- );- const appleStart = loginSource.indexOf("label={loginText('apple')}");- const appleEnd = loginSource.indexOf('testID="login.appleButton"', appleStart);- expect(appleStart).toBeGreaterThan(0);- expect(appleEnd).toBeGreaterThan(appleStart);- const appleBlock = loginSource.slice(appleStart, appleEnd);- expect(appleBlock).toContain('requireConsent(() =>');- expect(appleBlock).toContain("provider: 'apple'");- });-- it("企业 SSO 入口豁免:ssoEntryButton onPress 不过 requireConsent", () => {- // 取 SSO 圆钮自身的 JSX 段:label={loginText('ssoEntry')} → testID="login.ssoEntryButton"- const start = loginSource.indexOf("label={loginText('ssoEntry')}");- const end = loginSource.indexOf('testID="login.ssoEntryButton"');- expect(start).toBeGreaterThan(0);- expect(end).toBeGreaterThan(start);- const ssoEntryBlock = loginSource.slice(start, end);- expect(ssoEntryBlock).toContain("setSsoOrgMode(true)");- expect(ssoEntryBlock).not.toContain("requireConsent");- });-- it("P1 回归锁:容器 bounds 恒含协议行区间;弹窗前收键盘;radio 无 hitSlop", () => {- // ① 外层测量盒与内层设计容器都用 flowBottomDesignPx(622),协议行在父 bounds 内- expect(loginSource).toMatch(/height: flowBottomDesignPx \* groupScale/);- expect(loginSource).toMatch(/height: flowBottomDesignPx,/);- // ⑤ flow bottom 全步骤恒定(不随 showConsentRow 切换,消除步骤跳变)- expect(loginSource).not.toMatch(- /showConsentRow\s*\?\s*LOGIN_CONSENT_ROW\.bottomOverflow/,- );- // ② requireConsent 打开弹窗前收键盘(同意钮不被键盘遮挡)- expect(loginSource).toMatch(- /Keyboard\.dismiss\(\);[\s\S]{0,400}?setConsentDialogOpen\(true\)/,- );- });-- it("协议行 + 弹窗已挂载;安全区抬升含协议行溢出量;手机端无游客入口", () => {- expect(loginSource).toContain("<LoginConsentRow");- expect(loginSource).toContain("<LoginConsentDialog");- expect(loginSource).toContain("LOGIN_CONSENT_ROW.bottomOverflow");- expect(loginSource).toContain("loginText('consentStatement')");- // 手机/pad 为远程连接客户端,必须有账号——不加游客登录(产品拍板 2026-07-24;- // 断言不存在游客入口的具体接线:本地模式 IPC / 游客文案 key / 游客图标)- expect(loginSource).not.toContain("authEnterLocal");- expect(loginSource).not.toContain("localModeEntry");- expect(loginSource).not.toContain("GuestGlyph");- });-- it("协议链接经 Linking.openURL 打开(settings.tsx 同款模式)", () => {- expect(loginSource).toMatch(/Linking\.openURL\(\s*\n?\s*kind === 'terms'/);- });-});-describe("consent radio 无障碍(codex P1 双修:读屏标签 + 44pt 触摸区)", () => {it("触摸区常量:pressSize ≥88 设计px(phone ~0.5 缩放 → ≈44pt),行底 622 不变", () => {const { radio } = LOGIN_CONSENT_ROW;@@ -234,32 +182,7 @@ describe("consent radio 无障碍(codex P1 双修:读屏标签 + 44pt 触摸区));});- it("组件接线:命中区右下锚定 + 负 margin 占位回收 + 禁 hitSlop(历史结论回归锁)", () => {- // 行容器:top 上移 pressExpand、paddingTop 压回原内容带,行底不动- expect(controlsSource).toContain(- "const pressExpand = radio.pressSize - LOGIN_CONSENT_ROW.height",- );- expect(controlsSource).toContain("top: LOGIN_CONSENT_ROW.y - pressExpand");- expect(controlsSource).toContain("paddingTop: pressExpand");- // Pressable:88×88 bounds,右缘对齐 24 槽位右缘(不侵协议链接命中区)、底缘对齐行底- expect(controlsSource).toContain("height: radio.pressSize");- expect(controlsSource).toContain("width: radio.pressSize");- expect(controlsSource).toContain(- "marginLeft: -(radio.pressSize - radio.hitSize)",- );- expect(controlsSource).toMatch(/alignSelf: 'flex-end'/);- // hitSlop 方案已被否(父 bounds 裁剪、Android 界外触摸不派发),不许倒退- // (只拦属性用法 hitSlop= / hitSlop:,注释中说明历史结论的字样放行)- expect(controlsSource).not.toMatch(/hitSlop[=:]/);- });-it("读屏标签:accessibilityLabel = 协议声明剥标记纯文本,多语随 i18n 无新增 key", () => {- expect(controlsSource).toContain("accessibilityLabel={statementLabel}");- expect(controlsSource).toMatch(- /parseLegalSegments\(statement\)[\s\S]{0,120}?\.join\(''\)/,- );- expect(controlsSource).toContain('accessibilityRole="checkbox"');- expect(controlsSource).toContain("accessibilityState={{ checked }}");// 剥标记结果对全部 catalog 均为非空、无残留标记的完整句子for (const locale of ["zh-CN", "zh-TW", "en", "ja", "ko"] as const) {const label = parseLegalSegments(loginMessages[locale].consentStatement)@@ -270,21 +193,3 @@ describe("consent radio 无障碍(codex P1 双修:读屏标签 + 44pt 触摸区)}});});--describe("LoginSkinControls 接线(源码断言)", () => {- it("consent 组件只消费 colors.login.* 双态 token,弹窗按 groupScale 缩放", () => {- expect(controlsSource).toContain("login.consentRadioCheckedBg");- expect(controlsSource).toContain("login.consentOverlay");- expect(controlsSource).toContain("login.secondaryButtonBg");- expect(controlsSource).toContain("login.overlaySecondaryPressed");- // 弹窗 = stage 内全屏遮罩 + 680×380 设计坐标系整层缩放(与登录组同口径)- expect(controlsSource).toMatch(- /LOGIN_CONSENT_DIALOG[\s\S]*transform: \[\{ scale \}\]/,- );- // 区域确认与协议确认共用设计标准正文 26/40,不允许按文案临时缩字号。- expect(controlsSource).toContain("fontSize={D.body.font}");- expect(controlsSource).toContain("lineHeight={D.body.lineHeight}");- expect(controlsSource).not.toContain("compactBody");- expect(loginSource).not.toContain("compactBody");- });-});diff --git a/apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.ts b/apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.tsindex 9525df04a2..ff6b20fb98 100644--- a/apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.ts+++ b/apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.ts@@ -1,89 +1,46 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--/**- * 首启亮色门三态回归(Greptile P1:AsyncStorage 未决窗口透传系统暗色 →- * 判定后切亮 = 首启闪变)。三态语义:未决 = 'pending'(消费方不渲染品牌- * 内容,结构上不存在错误主题帧),判定后 'light'(真首启)/'passthrough'- * (老用户)。模块有 eager kick + 模块级缓存,每个用例 resetModules 后- * 动态 import 以获得干净状态。- */--type GateModule = typeof import('../loginFirstLaunchGate');--let resolveGetItem: (value: string | null) => void;-let rejectGetItem: (err: unknown) => void;-const setItem = vi.fn(() => Promise.resolve());--vi.mock('@react-native-async-storage/async-storage', () => ({- default: {- getItem: vi.fn(- () =>- new Promise<string | null>((resolve, reject) => {- resolveGetItem = resolve;- rejectGetItem = reject;- }),- ),- setItem,- },-}));--async function importFreshGate(): Promise<GateModule> {- vi.resetModules();- return import('../loginFirstLaunchGate');-}--async function flushMicrotasks(): Promise<void> {- await Promise.resolve();- await Promise.resolve();-}--beforeEach(() => {- setItem.mockClear();-});--describe('loginFirstLaunchGate 三态', () => {- it('AsyncStorage 未决时为 pending(不产出任何主题决定)', async () => {- const gate = await importFreshGate();- expect(gate.getLoginFirstLaunchGateState()).toBe('pending');- });-- it('读到空标记 → light(真首启),并落盘「已展示」标记', async () => {- const gate = await importFreshGate();- resolveGetItem(null);- await flushMicrotasks();- expect(gate.getLoginFirstLaunchGateState()).toBe('light');- expect(setItem).toHaveBeenCalledTimes(1);- });-- it('读到已有标记 → passthrough(老用户透传,不重写标记)', async () => {- const gate = await importFreshGate();- resolveGetItem('1750000000000');- await flushMicrotasks();- expect(gate.getLoginFirstLaunchGateState()).toBe('passthrough');- expect(setItem).not.toHaveBeenCalled();- });-- it('存储读取失败 → passthrough(不强制亮色,跟随系统兜底)', async () => {- const gate = await importFreshGate();- rejectGetItem(new Error('storage unavailable'));- await flushMicrotasks();- expect(gate.getLoginFirstLaunchGateState()).toBe('passthrough');- expect(setItem).not.toHaveBeenCalled();- });-});--describe('MobileLoginHandoffStage 消费 pending(源码结构断言,仓内无 render 框架)', () => {- it('pending 时先 return null,再进 ThemeOverrideProvider(不存在错误主题帧)', async () => {- const { readFileSync } = await import('node:fs');- const { resolve } = await import('node:path');- const source = readFileSync(- resolve(process.cwd(), 'src/components/MobileLoginHandoffStage.tsx'),- 'utf8',- );- const pendingReturn = source.indexOf('if (handoff.targetTheme == null)');- const overrideProvider = source.indexOf('<ThemeOverrideProvider');- expect(pendingReturn, 'pending 早退存在').toBeGreaterThan(-1);- expect(overrideProvider, 'ThemeOverrideProvider 渲染存在').toBeGreaterThan(-1);- expect(pendingReturn, 'pending 早退必须在渲染之前').toBeLessThan(overrideProvider);+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import React from 'react';+import { describe, expect, it, vi } from 'vitest';+import { resolveStartupSplashHandoff } from '../startupSplashContinuity';++// Greptile P1 / DESIGN §16.5: do not flash the system dark theme while first-launch+// storage is pending. Evaluate the real eager module per boot, without resetting+// the runner's dependency graph, and execute its actual brand-stage consumer.+const gateCode = ts.transpileModule(readFileSync(resolve(process.cwd(), 'src/auth/loginFirstLaunchGate.ts'), 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;+const stageAst = ts.createSourceFile('stage.tsx', readFileSync(resolve(process.cwd(), 'src/components/MobileLoginHandoffStage.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const stageNode = stageAst.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'MobileLoginHandoffStage');+if (!stageNode) throw new Error('brand-stage entry missing');+const stageCode = ts.transpileModule(stageNode.getText(stageAst), { compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.React } }).outputText;++describe('loginFirstLaunchGate boot and stage rendering', () => {+ it.each([null, 'already-shown', 'storage-error'])('keeps branding hidden until storage resolves to %j', async (value) => {+ let resolveRead!: (value: string | null) => void;+ let rejectRead!: (error: Error) => void;+ const getItem = vi.fn(() => new Promise<string | null>((resolve, reject) => { resolveRead = resolve; rejectRead = reject; }));+ const setItem = vi.fn(async () => undefined);+ const exports: Record<string, any> = {};+ runInNewContext(gateCode, { exports, require: (id: string) => id === 'react' ? {} : { __esModule: true, default: { getItem, setItem } } });+ const stageExports: Record<string, any> = {};+ runInNewContext(stageCode, {+ exports: stageExports, React, resolveStartupSplashHandoff,+ useLoginFirstLaunchLight: exports.getLoginFirstLaunchGateState, useTheme: () => ({ mode: 'dark' }),+ ThemeOverrideProvider: 'theme-provider', MobileLoginHandoffStageInner: 'brand-stage',+ });+ expect(exports.getLoginFirstLaunchGateState()).toBe('pending');+ expect(stageExports.MobileLoginHandoffStage({})).toBeNull();+ if (value === 'storage-error') rejectRead(new Error('storage unavailable'));+ else resolveRead(value);+ await Promise.resolve();+ await Promise.resolve();+ expect(exports.getLoginFirstLaunchGateState()).toBe(value === null ? 'light' : 'passthrough');+ const rendered = stageExports.MobileLoginHandoffStage({ testID: 'fixture' });+ expect(rendered.props.mode).toBe(value === null ? 'light' : 'dark');+ expect(rendered.props.children.props.testID).toBe('fixture');+ expect(getItem).toHaveBeenCalledOnce();+ expect(setItem).toHaveBeenCalledTimes(value === null ? 1 : 0);+ if (value === null) expect(setItem).toHaveBeenCalledWith('cindy.login.firstLaunchLightShown', expect.any(String));});});diff --git a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts b/apps/mobile/src/auth/__tests__/loginHandoffState.test.tsindex 041416559d..4995cb5912 100644--- a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts+++ b/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts@@ -231,3 +231,142 @@ describe('loginHandoff 接线(Provider/reporter 拓扑 + 清理,读源码断言)expect(loginSource).toContain("loginText('configTitle')");});});++// guard: credentials-and-local-storage and engineering-conventions section 3.2.+// Captcha must gate every auth request; scenario credentials must remain excluded from production.+describe("loginScenarioHarness authentication call-site boundary", () => {+const authContextSource = readFileSync(+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),+ 'utf8',+);+const metroConfigSource = readFileSync(resolve(process.cwd(), 'metro.config.js'), 'utf8');+describe('AuthContext 注入点(静态源码断言)', () => {+ it('经静态 import 使用 fixtures', () => {+ expect(authContextSource).toContain(+ "import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures'",+ );+ });++ it('guard 写死为 __DEV__ + EXPO_PUBLIC_LOGIN_SCENARIO(附录 A 值域 env)', () => {+ expect(authContextSource).toContain('devModeActive: __DEV__');+ expect(authContextSource).toContain('scenario: process.env.EXPO_PUBLIC_LOGIN_SCENARIO');+ });++ it('注入形态 = 真实 CindyAuthClient + fetch 构造参数(scenarioFetch ?? 真 fetch)', () => {+ expect(authContextSource).toContain(+ 'fetch: scenarioFetch ?? (async (input, init) => fetch(input, init))',+ );+ expect(authContextSource.match(/new CindyAuthClient\(/g)).toHaveLength(1);+ });++ it('metro.config 挂了生产 stub resolveRequest(build-time 排除双保险)', () => {+ expect(metroConfigSource).toContain("'@cindy/auth-client/fixtures'");+ expect(metroConfigSource).toContain("process.env.NODE_ENV === 'production'");+ expect(metroConfigSource).toContain('loginScenarios.production-stub.ts');+ });+});+});++// guard: credentials-and-local-storage and engineering-conventions section 3.2.+// Captcha must gate every auth request; scenario credentials must remain excluded from production.+describe("loginCaptcha authentication call-site boundary", () => {+describe('AuthContext captcha 闸接线(静态源码断言)', () => {+ const authContextSource = readFileSync(+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),+ 'utf8',+ );+ const loginSource = readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8');+ const captchaWebViewSource = readFileSync(+ resolve(process.cwd(), 'src/auth/LoginCaptchaWebView.tsx'),+ 'utf8',+ );++ it('discover 的 sole email_code 自动串发路径先过 ensureCaptchaGate', () => {+ const soleBranch = authContextSource.slice(+ authContextSource.indexOf("sole?.type === 'email_code'"),+ authContextSource.indexOf("updateLoginState(\n reduceAuthFlow(currentState, {\n type: 'code-requested'"),+ );+ expect(soleBranch).toContain("ensureCaptchaGate('email')");+ expect(soleBranch).toContain('requestCodeWithCaptchaFallback');+ });++ it('request-code 的 email/phone 都按 requiredFor 动作过闸,取消不派发', () => {+ const branch = authContextSource.slice(+ authContextSource.indexOf("if (action.type === 'request-code')"),+ authContextSource.indexOf("if (action.type === 'verify-code')"),+ );+ expect(branch).toContain('ensureCaptchaGate(action.kind)');+ expect(branch).toContain('if (!gate.proceed) return false;');+ expect(branch).toContain('requestCodeWithCaptchaFallback');+ expect(authContextSource).toContain('captchaRequiredActionForVerificationKind(kind)');+ expect(authContextSource).toContain('?action=${encodeURIComponent(action)}&lang=');+ });++ it('挑战页地址由构建区域 authApiBaseUrl + 共享路径常量拼出', () => {+ expect(authContextSource).toContain('CAPTCHA_CHALLENGE_PAGE_PATH');+ expect(authContextSource).toContain(+ "getMobileEndpointForRealm(BUILD_AUTH_REGION, 'authApiBaseUrl')",+ );+ });++ it('显示 captcha WebView 前先收起软键盘', () => {+ const challengeBranch = authContextSource.slice(+ authContextSource.indexOf('const runCaptchaChallenge'),+ authContextSource.indexOf('const ensureCaptchaGate'),+ );+ expect(authContextSource).toMatch(+ /import \{[^}]*\bKeyboard\b[^}]*\} from 'react-native';/,+ );+ expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeGreaterThan(-1);+ expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeLessThan(+ challengeBranch.indexOf('setCaptchaChallenge({ url });'),+ );+ });++ it('login.tsx 渲染 captcha WebView 模态并接回 resolveCaptchaChallenge', () => {+ expect(loginSource).toContain('auth.captchaChallenge');+ expect(loginSource).toContain('LoginCaptchaWebView');+ expect(loginSource).toContain('auth.resolveCaptchaChallenge');+ });++ it('captcha WebView 限制导航但不把客户端消息来源当作认证边界', () => {+ expect(captchaWebViewSource).toContain("originWhitelist={['*']}");+ expect(captchaWebViewSource).toContain('setSupportMultipleWindows={false}');+ expect(captchaWebViewSource).toContain('isAllowedLoginCaptchaNavigation(request, themedUrl)');+ expect(captchaWebViewSource).not.toContain('event.nativeEvent.url');+ expect(captchaWebViewSource).not.toMatch(/^\s*incognito(?:\s|=)/m);+ expect(captchaWebViewSource).toContain(+ 'parseCaptchaWebViewMessage(event.nativeEvent.data)',+ );+ expect(captchaWebViewSource).not.toContain('`${pageOrigin}/*`');+ });++ it('captcha WebView 使用 ThemeOverrideProvider 内的有效登录主题', () => {+ expect(captchaWebViewSource).toContain('const { colors, mode } = useTheme()');+ expect(captchaWebViewSource).toContain('withLoginCaptchaTheme(url, mode)');+ expect(captchaWebViewSource).toContain('source={{ uri: themedUrl }}');+ });++ it('captcha WebView 的 iOS/Android 渲染进程异常都进入失败重试态', () => {+ expect(captchaWebViewSource).toContain('onContentProcessDidTerminate={() => setFailed(true)}');+ expect(captchaWebViewSource).toContain('onRenderProcessGone={() => setFailed(true)}');+ });++ it('captcha WebView 超时后进入重试态,并在完成、重试或卸载时清理计时器', () => {+ expect(captchaWebViewSource).toContain('const CHALLENGE_TIMEOUT_MS = 120_000;');+ expect(captchaWebViewSource).toContain('const timeoutTimer = setTimeout(() => {');+ expect(captchaWebViewSource).toContain('return () => clearTimeout(timeoutTimer);');+ expect(captchaWebViewSource).toContain('}, [failed, generation, themedUrl]);');+ });++ it('captcha 打开时从 Android TalkBack 隐藏背景登录组与注销气泡', () => {+ expect(loginSource).toContain('const captchaChallengeOpen = auth.captchaChallenge !== null');+ expect(loginSource).toContain(+ 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen || handoffPhase',+ );+ expect(loginSource).toContain(+ 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen',+ );+ });+});+});diff --git a/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts b/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.tsindex febbf8fac0..e43a28b00e 100644--- a/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts+++ b/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts@@ -1,6 +1,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { runInNewContext } from 'node:vm';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';import {computeLoginKeyboardShift,@@ -16,7 +18,7 @@ import {* PR4b 键盘契约参数化单测(Step 5b.1 冻结向量;SC-7 slice pr4b keyboard 行)。* U-8b 硬标准:每例断言「当前输入框 + 主按钮完整可见」(clamped-fallback 除外,* 该模式按定义回退窄窗弹性规则);U-11=B:Android 悬浮键盘显式例外。- * 纯函数直测(判定引擎零 RN)+ hook/页面接线走读源码断言(仓内既有双轨形态)。+ * 纯函数直测 + 真 hook 事件回调与页面坐标换算执行,不以源码字面量替代行为。*/// 基线场景(iPhone 15 档 393×852 pt;union = 输入框顶(158)到主按钮底(380),@@ -225,62 +227,66 @@ describe('loginKeyboard U-8b 键盘可见性硬标准(参数化冻结向量)', (});});-describe('loginKeyboard 接线(hook 订阅拓扑 + 登录页测量拓扑,读源码断言)', () => {- const hookSource = readFileSync(- resolve(process.cwd(), 'src/session/useMobileKeyboardState.ts'),- 'utf8',- );- const loginSource = readFileSync(- resolve(process.cwd(), 'app/(auth)/login.tsx'),- 'utf8',- );- const stageSource = readFileSync(- resolve(process.cwd(), 'src/components/MobileLoginHandoffStage.tsx'),- 'utf8',- );-- it('iOS 订阅升级(v6.7):will show/hide + keyboardWillChangeFrame,卸载全移除', () => {- expect(hookSource).toContain("Keyboard.addListener('keyboardWillChangeFrame'");- expect(hookSource).toContain("Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow'");- expect(hookSource).toContain("Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide'");- expect(hookSource).toContain('for (const subscription of subscriptions) subscription.remove();');- });-- it('v5 冻结测量拓扑:外层未变换 wrapper measureInWindow,内层 translate 容器施加位移', () => {- expect(loginSource).toContain('measureInWindow');- expect(loginSource).toContain('外层未变换测量 wrapper');- expect(loginSource).toContain('translateY: -keyboardShift');- expect(loginSource).toContain('computeLoginKeyboardShift');- // 候选层收在面板内:停靠锚恒为面板底,悬浮键盘 union 仍纳入候选层。- expect(loginSource).toContain(- 'LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight',- );- expect(loginSource).toContain(- 'panelBottomY: groupBaseline.y + loginSizes.panelHeight * groupScale',- );- expect(loginSource).toContain(- 'height: (controlsUnionBottom - LOGIN_CONTROL.inputY) * groupScale',- );- expect(loginSource).toContain('LOGIN_CONTROL.inputY * groupScale');- // Android 未缩窗兜底:page 跟踪全高 + 传系统栏底(computeDockedKeyboardTop)- expect(loginSource).toContain('fullViewportHeight');- expect(loginSource).toContain('systemBarBottom: insets.bottom');- });+// Existing vectors cover the engine. These production callbacks additionally prove+// iOS frame changes reach it and that unmount removes native subscriptions (U-8b/U-11).+const hookAst = ts.createSourceFile('keyboard.ts', readFileSync(resolve(process.cwd(), 'src/session/useMobileKeyboardState.ts'), 'utf8'), ts.ScriptTarget.Latest, true);+const hook = hookAst.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'useLoginKeyboardRect');+if (!hook) throw new Error('login keyboard hook missing');+const hookCode = ts.transpileModule(hook.getText(hookAst), { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;+const loginAst = ts.createSourceFile('login.tsx', readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const coordinates: ts.VariableStatement[] = [];+function findCoordinates(node: ts.Node) {+ if (ts.isVariableStatement(node) && node.declarationList.declarations.some(decl => ts.isIdentifier(decl.name) && ['ssoOrgHistoryBottom', 'controlsUnionBottom', 'shiftResult'].includes(decl.name.text))) coordinates.push(node);+ ts.forEachChild(node, findCoordinates);+}+findCoordinates(loginAst);+if (coordinates.length !== 3) throw new Error('login keyboard coordinate block missing');+const coordinatesCode = ts.transpileModule(coordinates.map(node => node.getText(loginAst)).join(String.fromCharCode(10)), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;- it('品牌层随键盘整体上顶(demo kb-shift 同构),纯平底锚定根 View 不动', () => {- expect(stageSource).toContain('keyboardShiftPx');- expect(stageSource).toContain('translateY: -keyboardShiftPx');- // 背景钉在根 View 的 backgroundColor 上,位于键盘位移层之外- // (源码顺序:根 View 底色声明先于位移容器;wave4 双红渐变叠层已撤,对齐 PR#104)- const backgroundAt = stageSource.indexOf('backgroundColor: colors.login.bgBase');- const shiftAt = stageSource.indexOf('translateY: -keyboardShiftPx');- expect(backgroundAt).toBeGreaterThan(0);- expect(shiftAt).toBeGreaterThan(backgroundAt);+describe('login keyboard native event and coordinate behavior', () => {+ it.each(['ios', 'android'])('updates native keyboard rectangles and unsubscribes on %s', (platform) => {+ let state: any = { visible: false, rect: null };+ let cleanup: (() => void) | undefined;+ const callbacks = new Map<string, (event: any) => void>();+ const removes: Array<ReturnType<typeof vi.fn>> = [];+ const exports: Record<string, any> = {};+ runInNewContext(hookCode, {+ exports, Platform: { OS: platform },+ useState: () => [state, (update: any) => { state = typeof update === 'function' ? update(state) : update; }],+ useEffect: (effect: () => (() => void)) => { cleanup = effect(); },+ Keyboard: { addListener: (event: string, callback: (event: any) => void) => {+ callbacks.set(event, callback);+ const remove = vi.fn(() => callbacks.delete(event)); removes.push(remove); return { remove };+ } },+ });+ exports.useLoginKeyboardRect();+ const prefix = platform === 'ios' ? 'keyboardWill' : 'keyboardDid';+ callbacks.get(prefix + 'Show')!({ endCoordinates: { screenX: 10, screenY: 500, width: 200, height: 300 } });+ expect(state).toEqual({ visible: true, rect: { x: 10, y: 500, width: 200, height: 300 } });+ if (platform === 'ios') {+ callbacks.get('keyboardWillChangeFrame')!({ endCoordinates: { screenX: 150, screenY: 450, width: 200, height: 300 } });+ expect(state.rect).toEqual({ x: 150, y: 450, width: 200, height: 300 });+ } else expect(callbacks.has('keyboardWillChangeFrame')).toBe(false);+ callbacks.get(prefix + 'Hide')!({});+ callbacks.get('keyboardWillChangeFrame')?.({ endCoordinates: { screenX: 150, screenY: 450, width: 200, height: 300 } });+ expect(state).toEqual({ visible: false, rect: null });+ cleanup!();+ expect(callbacks.size).toBe(0);+ for (const remove of removes) expect(remove).toHaveBeenCalledOnce();});- it('AndroidManifest 键盘配置零改动(方案 B):不出现 windowSoftInputMode 自定义', () => {- expect(loginSource).not.toContain('windowSoftInputMode');- expect(hookSource).not.toContain('windowSoftInputMode');- expect(stageSource).not.toContain('windowSoftInputMode');+ it.each([false, true])('includes expanded organization history in floating-keyboard avoidance (expanded=%s)', (expanded) => {+ const keyboard = { visible: true, rect: { x: 80, y: 520, width: 220, height: 200 } };+ const result = runInNewContext(`${coordinatesCode}+shiftResult`, {+ ssoOrgMode: true, ssoOrgHistoryOpen: expanded, ssoOrgHistory: ['one', 'two'],+ LOGIN_SSO_ORG_HISTORY: { y: 120, maxHeight: 120 },+ LOGIN_CONTROL: { x: 20, inputY: 0, width: 280, buttonY: 100, height: 20 },+ useMemo: (compute: () => any) => compute(), computeLoginKeyboardShift,+ groupBaseline: { x: 40, y: 500 }, loginSizes: { panelHeight: 150 }, groupScale: 1,+ keyboard, Platform: { OS: 'ios' }, stage: { viewportWidth: 393, viewportHeight: 852 },+ insets: { top: 59, bottom: 48 }, fullViewportHeight: 852,+ });+ expect(result).toEqual({ mode: 'floating-overlap', shift: expanded ? 220 : 100 });});-});+});\ No newline at end of filediff --git a/apps/mobile/src/auth/__tests__/loginScenarioHarness.test.ts b/apps/mobile/src/auth/__tests__/loginScenarioHarness.test.tsindex 5bfeb00ca0..e2c6b5a1ce 100644--- a/apps/mobile/src/auth/__tests__/loginScenarioHarness.test.ts+++ b/apps/mobile/src/auth/__tests__/loginScenarioHarness.test.ts@@ -1,49 +1,8 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import { CindyAuthClient } from '@cindy/auth-client';import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';-/**- * 移动端登录 scenario harness 接线测试(implementation-plan Step 0 WHAT4 / SC-1)。- *- * AuthContext.tsx 整模块依赖 expo/RN 运行时,node vitest 不宜加载——注入点用- * 读源码断言(与仓内既有模式一致),guard 行为用 fixtures 纯函数断言:- * 非 __DEV__(devModeActive=false)下 harness 全部失效(production-mode 断言)。- */-const authContextSource = readFileSync(- resolve(process.cwd(), 'src/auth/AuthContext.tsx'),- 'utf8',-);-const metroConfigSource = readFileSync(resolve(process.cwd(), 'metro.config.js'), 'utf8');--describe('AuthContext 注入点(静态源码断言)', () => {- it('经静态 import 使用 fixtures', () => {- expect(authContextSource).toContain(- "import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures'",- );- });-- it('guard 写死为 __DEV__ + EXPO_PUBLIC_LOGIN_SCENARIO(附录 A 值域 env)', () => {- expect(authContextSource).toContain('devModeActive: __DEV__');- expect(authContextSource).toContain('scenario: process.env.EXPO_PUBLIC_LOGIN_SCENARIO');- });-- it('注入形态 = 真实 CindyAuthClient + fetch 构造参数(scenarioFetch ?? 真 fetch)', () => {- expect(authContextSource).toContain(- 'fetch: scenarioFetch ?? (async (input, init) => fetch(input, init))',- );- expect(authContextSource.match(/new CindyAuthClient\(/g)).toHaveLength(1);- });-- it('metro.config 挂了生产 stub resolveRequest(build-time 排除双保险)', () => {- expect(metroConfigSource).toContain("'@cindy/auth-client/fixtures'");- expect(metroConfigSource).toContain("process.env.NODE_ENV === 'production'");- expect(metroConfigSource).toContain('loginScenarios.production-stub.ts');- });-});-describe('guard 行为(production-mode 断言)', () => {it('非 __DEV__(devModeActive=false)→ 即使 env 设置了 scenario 也恒 null', () => {expect(diff --git a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts b/apps/mobile/src/auth/__tests__/loginSkinStates.test.tsindex a51a774e33..9ef0235606 100644--- a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts+++ b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts@@ -1,6 +1,12 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';+import * as React from 'react';+import ts from 'typescript';+import * as loginLayout from '../loginSkinLayout';+import { isCompleteCnPhone, sanitizeCnPhoneInput, toCnE164, CN_PHONE_PREFIX } from '../cnPhone';+import { isValidEmail } from '@cindy/auth-client';+import { canResumePendingConsent, makeConsentStamp } from '../consentGate';import {CindyAuthClient,@@ -33,10 +39,6 @@ const loginSource = readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'),'utf8',);-const controlsSource = readFileSync(- resolve(process.cwd(), 'src/components/LoginSkinControls.tsx'),- 'utf8',-);function makeClient(scenario: string, region: AuthRegion = 'cn') {return new CindyAuthClient({@@ -48,31 +50,118 @@ function makeClient(scenario: string, region: AuthRegion = 'cn') {});}-describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {- it('initializes on mount without using the explicit cancel action', () => {- const start = loginSource.indexOf('initializedLoginRef.current = true;');- expect(start).toBeGreaterThan(-1);- const effect = loginSource.slice(start, loginSource.indexOf('}, [additionalAccount, auth]);', start));- expect(effect).toContain("dispatchLoginAction({ type: 'initialize' })");- expect(effect).not.toContain("type: 'reset'");- expect(loginSource).toContain("dispatchLoginAction({ type: 'reset' })");+const loginTree = ts.createSourceFile('login.tsx', loginSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const renderCallbacks = new Map<string, string>();+function readRenderCallbacks(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text.startsWith('render') && node.initializer && ts.isArrowFunction(node.initializer)) {+ renderCallbacks.set(node.name.text, ts.transpileModule('const render = ' + node.initializer.getText(loginTree), {+ compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },+ }).outputText);+ }+ ts.forEachChild(node, readRenderCallbacks);+}+readRenderCallbacks(loginTree);+function productionRender(name: string, state: any, overrides: Record<string, unknown> = {}) {+ const components = Object.fromEntries(['LoginPanel', 'LoginTitleBlock', 'LoginPrimaryButton', 'LoginSkinPhoneInput', 'LoginSkinInput', 'LoginSocialRow', 'LoginSocialButton', 'LoginSocialGlyph', 'AppleLogoGlyph', 'LoginErrorText', 'LoginTextLinkSlot', 'LoginSsoOrgHistoryList', 'LoginMethodRow', 'LoginTextAction', 'LoginResendCountdown', 'LoginLoadingRing', 'CodeInput'].map((key) => [key, key]));+ const bindings = { React, ...loginLayout, ...components, isValidEmail, CN_PHONE_PREFIX, isCompleteCnPhone, sanitizeCnPhoneInput, toCnE164,+ auth: { loginState: state, isBusy: false, dispatchLoginAction: vi.fn(async () => undefined), clearAuthError: vi.fn() },+ loginText: (key: string) => key, authErrorText: (code: string) => code,+ identifierKind: 'phone', identifier: '13800000000', identifierFormatError: null, disabled: false, error: null,+ backNode: null, errorNode: null, accountRecoveryNode: null, resendDeadline: null, ssoOrgMode: false, ssoOrg: '', ssoOrgHistory: [], ssoOrgHistoryOpen: false,+ socialProviderModes: new Map([['apple', 'native'], ['google', 'browser']]),+ requireConsent: vi.fn((action: () => void) => action()), Platform: { OS: 'android' },+ LoginConsentRow: 'LoginConsentRow', consentAccepted: false, setConsentAccepted: vi.fn(), openLegalLink: vi.fn(),+ getSsoOrgHistorySnapshot: () => [], ssoOrgEditedRef: { current: false },+ verificationCode: '', bindingContact: '', bindingCode: '', ssoVerificationCode: '', styles: {},+ socialLabel: (provider: string) => provider, socialButtonTestId: (provider: string) => provider,+ setIdentifier: vi.fn(), setIdentifierFormatError: vi.fn(), setVerificationCode: vi.fn(), setBindingContact: vi.fn(), setBindingCode: vi.fn(),+ setSsoOrgMode: vi.fn(), setSsoOrg: vi.fn(), setSsoOrgHistoryOpen: vi.fn(), setSsoOrgHistory: vi.fn(),+ ...overrides };+ const compiled = renderCallbacks.get(name);+ if (!compiled) throw new Error('Missing production login renderer: ' + name);+ const render = new Function(...Object.keys(bindings), compiled + '\nreturn render;')(...Object.values(bindings));+ return { tree: render(), bindings };+}+function control(tree: any, id: string): any {+ if (!tree || typeof tree !== 'object') return undefined;+ if (Array.isArray(tree)) return tree.map((child) => control(child, id)).find(Boolean);+ if (tree.props?.testID === id) return tree.props;+ return control(tree.props?.children, id);+}++describe('production login state renderers', () => {+ it.each(['phone', 'email', 'apple', 'google', 'sso'])('routes the actual %s entry through its consent authority', (entry) => {+ const requireConsent = vi.fn();+ const state = { step: 'identifier', providers: { social: ['apple', 'google'], phone: true, email: true } };+ const rendered = productionRender('renderIdentifier', state, { requireConsent, identifierKind: entry === 'email' ? 'email' : 'phone', identifier: entry === 'email' ? '[email protected]' : '13800000000' });+ if (entry === 'phone' || entry === 'email') control(rendered.tree, 'login.continueButton').onPress();+ else control(rendered.tree, entry === 'sso' ? 'login.ssoEntryButton' : 'login.' + entry + 'Button').onPress();+ expect(rendered.bindings.auth.dispatchLoginAction).not.toHaveBeenCalled();+ if (entry === 'sso') {+ expect(requireConsent).not.toHaveBeenCalled();+ expect(rendered.bindings.setSsoOrgMode).toHaveBeenCalledWith(true);+ } else expect(requireConsent).toHaveBeenCalledOnce();});- it('keeps retained accounts reachable after the active session expires', () => {- expect(loginSource).toContain(- "import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';",- );- expect(loginSource).toContain(- 'void auth.syncSavedAccounts().catch(() => undefined);',- );- expect(loginSource).toContain('auth.savedAccounts.length > 0');- expect(loginSource).toContain('testID="login.accountSwitcher"');- expect(loginSource).toContain("label={t('devices.list.accounts.title')}");- expect(loginSource).toContain('<AccountSwitcherSheet');- expect(loginSource).toContain('hasRunningTasks={hasRunningTasks}');- expect(loginSource).toContain('remoteSessionStore.isSessionRunning(session.id)');+ // This is the actual gate from the page, including its stale-auth stamp check.+ it.each(['agree', 'dismiss', 'context-changed'])('continues only the still-authorized consent action: %s', (finish) => {+ const names = new Set(['requireConsent', 'agreeConsent', 'dismissConsent']);+ const fragments: string[] = [];+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && names.has(node.name.text) && node.initializer) fragments.push('const ' + node.name.text + ' = ' + node.initializer.getText(loginTree) + ';');+ ts.forEachChild(node, visit);+ }+ visit(loginTree);+ const auth = { loginState: { step: 'identifier' }, isBusy: false, isAuthenticated: false };+ const bindings = { consentAccepted: false, pendingConsentAction: { current: null }, auth, additionalAccount: false, makeConsentStamp, canResumePendingConsent,+ Keyboard: { dismiss: vi.fn() }, setConsentDialogOpen: vi.fn(), setConsentAccepted: vi.fn(), persistPrivacyConsent: vi.fn() };+ const code = ts.transpileModule(fragments.join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const gate = new Function(...Object.keys(bindings), code + '\nreturn {requireConsent, agreeConsent, dismissConsent};')(...Object.values(bindings));+ const action = vi.fn();+ gate.requireConsent(action);+ expect(bindings.Keyboard.dismiss).toHaveBeenCalledOnce();+ expect(action).not.toHaveBeenCalled();+ if (finish === 'context-changed') auth.loginState.step = 'completed';+ if (finish === 'dismiss') gate.dismissConsent(); else gate.agreeConsent();+ expect(action).toHaveBeenCalledTimes(finish === 'agree' ? 1 : 0);+ expect(bindings.pendingConsentAction.current).toBeNull();+ expect(bindings.setConsentDialogOpen).toHaveBeenLastCalledWith(false);+ });++ it('enforces phone validation and E.164 dispatch through the actual submit handler', () => {+ const state = { step: 'identifier', providers: { social: [], phone: true, email: true } };+ const invalid = productionRender('renderIdentifier', state, { identifier: '12' });+ control(invalid.tree, 'login.identifierInput').onSubmitEditing();+ expect(invalid.bindings.auth.dispatchLoginAction).not.toHaveBeenCalled();+ expect(invalid.bindings.setIdentifierFormatError).toHaveBeenCalledWith('phone');+ const valid = productionRender('renderIdentifier', state);+ control(valid.tree, 'login.identifierInput').onSubmitEditing();+ expect(valid.bindings.requireConsent).toHaveBeenCalledTimes(1);+ expect(valid.bindings.auth.dispatchLoginAction).toHaveBeenCalledWith({ type: 'request-code', kind: 'phone', identifier: '+8613800000000' });});+ it.each(['', '123456'])('only enables verification with a complete code %j', (verificationCode) => {+ const rendered = productionRender('renderVerification', { step: 'verification-code', kind: 'phone', identifier: '+8613800000000' }, { verificationCode });+ const submit = control(rendered.tree, 'login.verifyButton');+ expect(submit.disabled).toBe(verificationCode.length !== 6);+ submit.onPress();+ if (verificationCode.length === 6) expect(rendered.bindings.auth.dispatchLoginAction).toHaveBeenCalledWith(expect.objectContaining({ type: 'verify-code', code: verificationCode }));+ else expect(rendered.bindings.auth.dispatchLoginAction).not.toHaveBeenCalled();+ });++ it('renders the correct binding control for each authoritative substate', () => {+ const contact = productionRender('renderBinding', { step: 'binding', bindType: 'phone', codeRequested: false });+ expect(control(contact.tree, 'login.bindingContactInput')).toBeDefined();+ expect(control(contact.tree, 'login.bindingSendButton').disabled).toBe(true);+ expect(control(contact.tree, 'login.bindingVerifyButton')).toBeUndefined();+ const code = productionRender('renderBinding', { step: 'binding', bindType: 'email', codeRequested: true, contact: '[email protected]' });+ expect(control(code.tree, 'login.bindingVerifyButton')).toBeDefined();+ expect(control(code.tree, 'login.bindingSendButton')).toBeUndefined();+ });+});++describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {+it('identifier:providers 真链加载→identifier 步骤,区域定形态(无 tabs)/输入/主按钮/圆钮行接线', async () => {const client = makeClient('providers:both');const providers = await client.getProviders();@@ -80,38 +169,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {expect(state).toMatchObject({ step: 'identifier' });expect(providers.email).toBe(true);expect(providers.phone).toBe(true);- // 渲染层:皮肤组件 + 既有 testID verbatim。- // 双 tab 已按用户拍板(2026-07-21 分区互斥)移除:形态由构建区域确定性推导。- expect(loginSource).not.toContain('LoginIdTabs');- expect(loginSource).toContain(- 'resolveIdentifierMethod(AUTH_REGION, auth.loginState.providers)',- );- expect(loginSource).toContain('testID="login.identifierInput"');- expect(loginSource).toContain('testID="login.continueButton"');- expect(loginSource).toContain('testID="login.ssoEntryButton"');- // Apple 圆钮(当前平台有可用路径时)计入行 count:apple 1 + nonAppleProviders + SSO 1- expect(loginSource).toContain("socialProviders.includes('apple') ? 1 : 0");- expect(loginSource).toContain('nonAppleProviders.length');- expect(loginSource).toContain(- "void auth.dispatchLoginAction({ type: 'discover', email: value })",- );- });-- it('identifier-phone:+86 固定前缀 + 11 位大陆手机号门槛 + E.164 提交', () => {- expect(loginSource).toContain('<LoginSkinPhoneInput');- expect(loginSource).toContain('prefix={CN_PHONE_PREFIX}');- expect(loginSource).toContain('setIdentifier(sanitizeCnPhoneInput(text))');- // 号段不合法本地拦截:2026-07-22 MT 起改为设计稿定义的红字错误态- // (setIdentifierFormatError('phone') 后 return,不再静默 return),- // 门槛判定 !isCompleteCnPhone(identifier) 与 E.164 提交保持不变。- expect(loginSource).toContain('if (!isCompleteCnPhone(identifier)) {');- expect(loginSource).toContain("setIdentifierFormatError('phone');");- expect(loginSource).toContain('identifier: toCnE164(identifier),');- expect(loginSource).toContain('!isCompleteCnPhone(identifier)');- expect(controlsSource).toContain(- 'testID={testID ? `${testID}.shell` : undefined}',- );- expect(controlsSource).toContain('style={styles.phonePrefix}');});it('identifier-input:输入 focus/filled 切 controlBorderActive 边与 Bold 墨字(figma §4.1)', async () => {@@ -121,13 +178,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {'global',).getProviders();expect(providers.social).toEqual(['apple', 'google']);- expect(controlsSource).toContain('const active = focused || filled;');- expect(controlsSource).toContain('colors.login.controlBorderActive');- expect(controlsSource).toContain(- 'active ? fontWeight.bold : fontWeight.regular',- );- expect(controlsSource).toContain('colors.login.controlPlaceholder');- expect(controlsSource).toContain('colors.login.loginError');});it('method-choice:sso:single 真链→企业/个人双行,dispatch 措辞 verbatim', async () => {@@ -142,15 +192,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {if (state.step !== 'method-choice') throw new Error('unreachable');expect(state.methods.filter((m) => m.type === 'sso')).toHaveLength(1);expect(state.methods.some((m) => m.type === 'email_code')).toBe(true);- expect(loginSource).toContain('<LoginMethodRow');- expect(loginSource).toContain(- 'testID={`login.sso.${method.connectionId}`}',- );- expect(loginSource).toContain('testID="login.emailCodeButton"');- expect(loginSource).toContain("type: 'start-sso',");- expect(loginSource).toContain(- 'label: method.connectionName || method.orgName,',- );});it('method-choice-multi:sso:multi 真链→多 connection 单行「以企业身份登录 · <name>」保留', async () => {@@ -164,10 +205,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {if (state.step !== 'method-choice')throw new Error('expected method-choice');expect(state.methods.filter((m) => m.type === 'sso')).toHaveLength(2);- // 多 connection 时标题拼接措辞 verbatim(单行,不拆副行)- expect(loginSource).toContain(- "`${loginText('enterpriseLogin')} · ${method.connectionName || method.orgName}`",- );});it('method-choice-personal:纯邮箱 discovery→emailCode 主行(无 SSO 上下文)', async () => {@@ -181,45 +218,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {if (state.step !== 'method-choice')throw new Error('expected method-choice');expect(state.methods).toEqual([{ type: 'email_code' }]);- // 无 SSO 时按钮文案退回「发送邮箱验证码」,个人身份措辞仅在有 SSO 时出现- expect(loginSource).toContain(- "ssoMethods.length > 0 ? 'personalLogin' : 'emailCode'",- );- expect(loginSource).toContain('icon="person"');- });-- it('sso-org-empty:企业 ID 子视图空态接线(placeholder/hint/返回)', () => {- expect(loginSource).toContain('testID="login.ssoOrgInput"');- expect(loginSource).toContain('hydrateSsoOrgHistory()');- expect(loginSource).toContain('<LoginSsoOrgHistoryList');- expect(loginSource).toContain('accessibilityRole="combobox"');- expect(loginSource).not.toContain('setSsoOrgHistoryOpen(history.length > 1)');- expect(loginSource).not.toContain('setSsoOrgHistoryOpen(ssoOrgHistory.length > 1)');- expect(loginSource).toContain("loginText('ssoOrgTitle')");- expect(loginSource).toContain("loginText('ssoOrgPlaceholder')");- expect(loginSource).toContain("loginText('ssoOrgHint')");- expect(LOGIN_SSO_ORG_HISTORY.y).toBe(- LOGIN_CONTROL.inputY + LOGIN_CONTROL.height + 8,- );- expect(- LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight,- ).toBeLessThanOrEqual(loginSizes.panelHeight);- expect(controlsSource).toContain('showsVerticalScrollIndicator={false}');- // 返回钮:子视图退回首屏输入(不整体 reset)- expect(loginSource).toContain('setSsoOrgMode(false);');- });-- it('sso-org-filled:企业 ID 直接发现,仅在状态机判定跨区后确认', () => {- expect(loginSource).toContain("type: 'discover-sso-org'");- expect(loginSource).toContain(- 'setSsoOrgHistory(getSsoOrgHistorySnapshot())',- );- expect(loginSource).toContain("auth.loginState?.step === 'realm-confirmation'");- expect(loginSource).toContain("type: 'confirm-sso-realm'");- expect(loginSource).toContain("type: 'cancel-sso-realm'");- expect(loginSource).not.toContain('crossRegionConsent');- expect(loginSource).toContain('testID="login.ssoOrgContinueButton"');- expect(loginSource).toContain('disabled={disabled || !ssoOrg.trim()}');});it('sso-org-list:discoverSsoOrg 真链→method-choice(无邮箱上下文,行起点 148)', async () => {@@ -233,11 +231,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {methods,});expect(state.step).toBe('method-choice');- // 无邮箱上下文:副标题走 ssoOrgDetected,行起点用 sso-org 档(148)- expect(loginSource).toContain(- "loginText('ssoOrgDetected').replace('{org}', orgName)",- );- expect(loginSource).toContain('LOGIN_METHOD_ROW.firstRowTopSsoOrg');});it('verification-code-empty:request-code 真链→步骤态,居中验证码输入接线', async () => {@@ -253,29 +246,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {kind: 'phone',identifier: '13800000000',});- expect(loginSource).toContain('testID="login.codeInput"');- expect(loginSource).toContain('center');- expect(loginSource).toContain(- "`${loginText('codeSentTo')} ${state.identifier}`",- );- });-- it('verification-code-filled:6 位门槛与登录钮接线(login.verifyButton)', () => {- expect(loginSource).toContain('if (verificationCode.length !== 6) return;');- expect(loginSource).toContain(- 'disabled={disabled || verificationCode.length !== 6}',- );- expect(loginSource).toContain('testID="login.verifyButton"');- expect(loginSource).toContain("type: 'verify-code',");- });-- it('verification-code-loading:主按钮 busy spinner = 外层 Animated 旋转 + 静态 SVG', () => {- expect(loginSource).toContain('busy={auth.isBusy}');- // 仓规 7 RN 对应:useNativeDriver transform 循环,SVG 图形静止,仅 busy 期挂载- expect(controlsSource).toContain('useNativeDriver: true');- expect(controlsSource).toContain('Animated.loop(');- expect(controlsSource).toContain('<LoginSpinnerGlyph');- expect(controlsSource).toContain('{busy ? (');});it('account-selection:outcome:select-account 真链→双身份列表,方式行渲染', async () => {@@ -291,13 +261,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {throw new Error('expected account-selection');expect(state.accounts).toHaveLength(2);expect(state.accounts.map((a) => a.kind)).toEqual(['personal', 'org']);- expect(loginSource).toContain('testID={`login.account.${account.id}`}');- expect(loginSource).toContain(- "account.kind === 'org' ? 'enterprise' : 'person'",- );- expect(loginSource).toContain(- "account.orgName || account.email || loginText('personalAccount')",- );});it('binding-contact:outcome:binding-phone 真链→绑定阶段一(输入+发送)', async () => {@@ -313,21 +276,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {bindType: 'phone',codeRequested: false,});- expect(loginSource).toContain('testID="login.bindingContactInput"');- expect(loginSource).toContain('testID="login.bindingSendButton"');- expect(loginSource).toContain("type: 'request-binding-code',");- });-- it('binding-phone:+86 固定前缀与登录首屏同规则,11 位完整后才可发送验证码', () => {- expect(loginSource).toContain('const contactReady = isEmail');- expect(loginSource).toContain(': isCompleteCnPhone(bindingContact);');- expect(loginSource).toContain(- 'contact: isEmail ? bindingContact : toCnE164(bindingContact),',- );- expect(loginSource).toContain(- 'setBindingContact(sanitizeCnPhoneInput(text))',- );- expect(loginSource).toContain('disabled={disabled || !contactReady}');});it('binding-code:binding-code-requested→阶段二(验证码+「登录」钮)', async () => {@@ -352,9 +300,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {codeRequested: true,contact: '[email protected]',});- expect(loginSource).toContain('testID="login.bindingVerifyButton"');- // 阶段二按钮文案保留「登录」(signIn key)- expect(loginSource).toContain("type: 'verify-binding',");});it('browser-redirect:browser-started→panel + 64 loading 环 + 取消', () => {@@ -363,18 +308,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {label: 'Example SSO',});expect(state).toEqual({ step: 'browser-redirect', label: 'Example SSO' });- expect(loginSource).toContain('<LoginLoadingRing');- expect(loginSource).toContain('LOGIN_LOADING_RING.yBrowser');- expect(loginSource).toContain('testID="login.cancelBrowserButton"');- expect(loginSource).toContain(- "`${state.label} · ${loginText('browserSubtitle')}`",- );- });-- it('preparing:auth 未初始化伪态 loading 环接线(64 @(308,193))', () => {- expect(loginSource).toContain('renderPreparing');- expect(loginSource).toContain('LOGIN_LOADING_RING.yPreparing');- expect(loginSource).toContain('testID="login.panel.preparing"');});it('error:failed→error 步骤,retry + authErrorText 兜底接线', () => {@@ -388,12 +321,6 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {code: 'NETWORK_ERROR',recoverTo: 'identifier',});- expect(loginSource).toContain('testID="login.panel.error"');- expect(loginSource).toContain('testID="login.errorRetryButton"');- expect(loginSource).toContain(- "authErrorText(state.code) ?? loginText('errorFallback')",- );- expect(loginSource).toContain('testID="login.error"');});it('completed:outcome ok 真链→completed 瞬态,面板留空品牌保持', async () => {@@ -403,39 +330,5 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {const state = reduceAuthFlow(null, { type: 'outcome', outcome });if (state.step !== 'completed') throw new Error('expected completed');expect(state.membership.displayName).toBe('Scenario User');- expect(loginSource).toContain("auth.loginState?.step === 'completed'");- expect(loginSource).toContain('? null');- });-- it('no-loginstate:兜底单按钮 默认/busy 双格接线(login.retryButton)', () => {- expect(loginSource).toContain('testID="login.retryButton"');- expect(loginSource).toContain(- "label={auth.isBusy ? loginText('working') : loginText('continue')}",- );- expect(loginSource).toContain('testID="login.panel.noLoginState"');- // 状态机行为零改动:reset 重新拉起- expect(loginSource).toContain(- "void auth.dispatchLoginAction({ type: 'reset' });",- );- });-- it('SC-SOC-7:圆钮 onPress in-flight guard — disabled 时 no-op,非 disabled 正常派发(行为层,零视觉变化)', () => {- // 用户拍板(§10)砍的是 disabled/loading 视觉态,不是防重复提交行为;按规则 9- // 在调用点 handler 拦,复用既有 disabled 变量(auth.isBusy||!initialized||configIssues)。- // 零视觉变化:无 disabled attr/className/StateOverlay 视觉回填;in-flight 仅加- // accessibilityState.busy 无障碍语义(非视觉,对齐桌面 aria-disabled;见 LoginSkinButton),- // 不传原生 disabled——视觉/交互态不变。- // 渲染层读源码断言(login.tsx 依赖 expo/RN,node vitest 不加载,沿用仓内既有模式)。- // 1. in-flight guard 存在:两个圆钮 onPress 各一(social + ssoEntry),≥2 处- // FRAGILE:源码字面匹配——重排版空格仍匹配(\s* 容差),但变量改名(disabled→别的)或- // 改写为 if-block 会假失败;改 onPress guard 时同步更新此正则,或抽成纯函数测行为。- const guardMatches = loginSource.match(/if\s*\(\s*disabled\s*\)\s*return\s*;/g) ?? [];- expect(guardMatches.length).toBeGreaterThanOrEqual(2);- // 2. 非 in-flight 派发路径保留:iOS native + Global Android browser。- expect(loginSource).toMatch(/type:\s*'native-social',\s*provider/);- expect(loginSource).toContain("type: 'start-social-browser'");- // 3. SSO 非 in-flight 路径保留(clearAuthError + setSsoOrgMode)- expect(loginSource).toContain('auth.clearAuthError();');- expect(loginSource).toContain('setSsoOrgMode(true);');});});diff --git a/apps/mobile/src/auth/__tests__/loginSsoVerificationRender.test.ts b/apps/mobile/src/auth/__tests__/loginSsoVerificationRender.test.tsindex 49935cbe9a..237225a987 100644--- a/apps/mobile/src/auth/__tests__/loginSsoVerificationRender.test.ts+++ b/apps/mobile/src/auth/__tests__/loginSsoVerificationRender.test.ts@@ -1,56 +1,34 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it, vi } from 'vitest';+import * as React from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import ts from 'typescript';+import { describe, expect, it } from 'vitest';-/**- * renderSsoVerification 错误可见性回归(SC-SOC + P1-1):- * mobile 无 component render 框架,沿用仓内「读源码断言」模式验证结构不变量。- * 不变量:errorNode 必须在 `!state.codeRequested` 条件【之外】,两个子态都渲染——- * 否则首次「发送验证码」失败(codeRequested 仍 false)时错误不显示(silent failure,- * desktop 是常显的,双端须一致)。- */-vi.mock('expo-localization', () => ({- getLocales: () => [{ languageTag: 'zh-CN' }],-}));+// P1-1: a failed first code request leaves codeRequested=false; its error must+// still render inside the panel. Run the production callback in both substates.+const source = ts.createSourceFile('login.tsx', readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let callback: ts.Expression | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'renderSsoVerification') callback = node.initializer;+ ts.forEachChild(node, visit);+}+visit(source);+if (!callback) throw new Error('Missing production SSO verification callback');+const compiled = ts.transpileModule('const render = ' + callback.getText(source) + ';', { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;-const loginSource = readFileSync(- resolve(process.cwd(), 'app/(auth)/login.tsx'),- 'utf8',-);--describe('renderSsoVerification 错误可见性(P1-1:两子态都渲染错误)', () => {- const blockStart = loginSource.indexOf('const renderSsoVerification');- const block = loginSource.slice(- blockStart,- loginSource.indexOf('const renderBinding', blockStart),- );-- it('renderSsoVerification 存在且含 errorNode', () => {- expect(blockStart, 'renderSsoVerification exists').toBeGreaterThan(-1);- expect(block, 'block non-empty').toBeTruthy();- expect(block.indexOf('{errorNode}'), 'has errorNode').toBeGreaterThan(-1);- });-- it('errorNode 在 !state.codeRequested 条件之外(首次发码失败 codeRequested=false 时错误仍可见,非 silent failure)', () => {- // codeRequested=true 子态结尾 </> 之后的条件 ternary 结尾 )},errorNode 必须在其后(条件外)- const substateClose = block.lastIndexOf('</>');- expect(substateClose, 'codeRequested=true substate closes </>').toBeGreaterThan(-1);- const condClose = block.indexOf(')}', substateClose);- expect(condClose, 'ternary condition closes )}').toBeGreaterThan(-1);- const errorIdx = block.indexOf('{errorNode}', condClose);- expect(- errorIdx,- 'errorNode rendered OUTSIDE !codeRequested condition (visible in both substates)',- ).toBeGreaterThan(-1);- });-- it('验证码已发子态(codeRequested=true)仍渲染错误(errorNode 在 LoginPanel 内、条件外)', () => {- const errorIdx = block.indexOf('{errorNode}');- const panelClose = block.indexOf('</LoginPanel>');- expect(errorIdx, 'errorNode present').toBeGreaterThan(-1);- expect(panelClose, 'LoginPanel closes').toBeGreaterThan(-1);- expect(errorIdx, 'errorNode before LoginPanel close (stays in panel)').toBeLessThan(- panelClose,- );+describe('SSO verification error visibility (P1-1)', () => {+ it.each([false, true])('shows the request error inside the panel when codeRequested=%s', (codeRequested) => {+ const host = ({ children, label, testID }: any) => React.createElement('div', { 'data-testid': testID }, label, children);+ const bindings = { React, auth: { loginState: { step: 'sso-verification', codeRequested, targetMasked: 'a***@example.invalid' }, isBusy: false },+ ssoVerificationCode: '', disabled: false, error: 'Code request failed',+ setSsoVerificationCode: () => {}, loginText: (key: string) => key, backNode: null,+ errorNode: React.createElement('span', { role: 'alert' }, 'Code request failed'),+ LoginPanel: host, LoginTitleBlock: host, LoginPrimaryButton: host, LoginResendCountdown: host, CodeInput: host };+ const render = new Function(...Object.keys(bindings), compiled + '\nreturn render;')(...Object.values(bindings));+ const markup = renderToStaticMarkup(render());+ expect(markup).toContain('data-testid="login.panel.sso-verification"');+ expect(markup).toContain('<span role="alert">Code request failed</span>');+ expect(markup).toContain(codeRequested ? 'login.ssoVerificationVerifyButton' : 'login.ssoVerificationSendButton');});});diff --git a/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts b/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.tsindex 716ee0587f..65a6ab84c7 100644--- a/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts+++ b/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts@@ -1,3 +1,4 @@+// guard: credentials-and-local-storage.md: auth-owned migrations and automatic writes must fence current identity/generation before asynchronous account cleanup.import { readFileSync } from 'node:fs';import { resolve } from 'node:path';diff --git a/apps/mobile/src/update/playUpdateEntries.test.ts b/apps/mobile/src/update/playUpdateEntries.test.tsindex 5d3645da00..f9c13a8159 100644--- a/apps/mobile/src/update/playUpdateEntries.test.ts+++ b/apps/mobile/src/update/playUpdateEntries.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -81,9 +79,6 @@ describe('Google Play update entry points', () => {const { checkNow } = useBundleUpdatePrompt({ auto: true, channel: 'release' });await expect(checkNow()).resolves.toBe('skipped');expect(mocks.fetchLatest).not.toHaveBeenCalled();- // The root layout still mounts its independent startup content OTA gate.- const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');- expect(layout).toContain('const otaReady = useStartupOtaGate(channel);');});it('resume checks content OTA but never asks for the website APK', async () => {@@ -98,11 +93,6 @@ describe('Google Play update entry points', () => {});it('settings passes no website check and can still check content OTA', async () => {- const settings = readFileSync(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');- expect(settings).toContain('isGooglePlayInstallation: playManagedUpdates,');- expect(settings).toContain('checkBundleUpdate: bundleCheckEnabled ? checkBundleUpdate : undefined,');- expect(settings).toContain('const updateCheckEnabled = bundleCheckEnabled || updatesEnabled;');- expect(settings).toContain("t('settings.version.googlePlayContentUpdateUnavailable')");await expect(runManualUpdateCheck({checkBundleUpdate: undefined,otaEnabled: true,diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 24ca448248..2e07d79f91 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -47,6 +47,18 @@ Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时分 4 片是 2、2、2、0)。runner 原来只在「文件数少于分片数」时补 `--passWithNoTests`,本机 4/4 分片因此有 6 个包报 `NO_TESTS_REQUIRED`;现已按 Vitest 的切分方式判断空分片。+审查恢复到 92 个 Desktop guard 文件后,Windows CI 暴露了另一个启动边界:逐项传递+exclude 会超过 `vitest.cmd` 的 8,191 字符限制,Desktop 尚未收集测试便退出。runner 和+`benchmark:desktop-workers` 现共用 Windows 的直接 Node 启动器,保留完整参数和工具 PATH;+Linux 及 package script 的启动方式不变。回归测试通过真实 runner 传入超过 8,191 字符的+排除列表并执行已有小型测试,同时验证空格、中文、引号与 shell 特殊字符原样到达子进程。++同轮审查补齐了 workspace `process.cwd()` 源码路径、本地 timeout 包装和常量时长检测,+并修正 `afterEach` 不应追溯影响首例的假时钟判断。源码读取按各自绑定区分用途:+送入 Function/VM 执行的生产回调继续留在 unit;同一读取还用于源码文字断言时仍须分层,+无关的执行不能豁免它。device-link client 的四处 ≥100ms 等待改用假时钟,288 条原有+用例整份通过,约 17.2 秒;未通过新增基线或删除结果断言来放行。+### 2026-10-16 实验与落地本机 Windows、32 CPU、Desktop 8 worker。隔离方式三组用同一分片(869 个文件)连续对照:@@ -63,15 +75,15 @@ Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时每片的 worker 时间里,收集(导入模块)约 325–350 秒,执行测试 250–480 秒,环境初始化 105–127 秒,准备约 46 秒;后三项主要来自逐文件隔离。整体切换隔离方式会破坏正确性,所以改为逐个修掉开销最大的-文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 438 个-文件,只减不增,见 engineering-conventions.md §3.2「性能预算」)。修完 `codexProxyHost` 后,最慢的+文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(存量计数+只减不增,见 engineering-conventions.md §3.2「性能预算」)。修完 `codexProxyHost` 后,最慢的单个文件从 138 秒降到约 32 秒,不再由一个文件决定分片下限。优化后按 CI 方式(runner、4 分片、Windows tar、无 `XDT_*`)完整重跑:门禁、`test:runner`、guard、typecheck全部通过;4 个分片只有 `taskWorkspace.test.ts` 1 条 symlink 能力失败。各片 `maker-core` 从 71/21/54/108 秒降到 34/5/27/55 秒;含 `codexProxyHost` 的 Desktop 分片从 144 秒降到 117 秒。代码没动的 Desktop 分片同时慢了约 20%,说明本机(同时运行其他重负载程序)整片墙钟有 ±20% 的波动,收益以上表的同机连续对照为准,-CI 时长仍要用首次 4 分片 CI 实测确认。+这是初始实现的本机对照;最终合并版本以 PR CI 的完整复跑为准。后续候选(每项都要在同一 runner、同一分片配置下实测后才能声称收益):@@ -89,19 +101,21 @@ CI 时长仍要用首次 4 分片 CI 实测确认。- 初始删除 81 个文件(488 条用例);独立审查发现其中包含缺少等价覆盖的权限、竞态、远程路由和设计契约,已恢复 30 个完整文件,并从 `homeUsageDashboardSource.test.ts` 保留账号隔离的 3 条契约(含同步主干时保留的 `botChatSurface.test.ts`)。后续逐文件复核另保留分享脱敏的两条契约、- 侧栏折叠时通知订阅归属的一条契约。最终相对原始基线删除 47 个文件,+ 侧栏折叠时通知订阅归属的一条契约。随后将 Mobile 混合文件逐项行为化、合并必要原生契约,+ 最终相对原始基线删除 54 个文件(包含已迁入其他文件的覆盖),不能沿用最初的「488 条无效用例」结论。`FileTreeView.horizontalScroll.test.tsx` 真实挂载组件并断言可见宽度,已恢复。IM 启动补全、空草稿水合与语音切换、预览误发送、远程扫描旧回包、图片标注误关闭、Orca 隐藏/可见时的通知生命周期,改由真实生产入口或组件行为回归覆盖。原生源码检测包含 Swift、C/C++、Rust 等;必要的跨原生协议、权限与生命周期契约进入required guard,执行脚本和 JSON/二进制资源不作为源码字面量断言。-- 207 个 PARTIAL 文件(2,874 条用例,其中约 991 条是静态或重复接线候选)保留:它们与续跑、设备链、+- 初始审计的 207 个 PARTIAL 文件(2,874 条用例,其中约 991 条是静态或重复接线候选)与续跑、设备链、账户切换、Pi、权限和竞速回归混在一起,只能在补上等价的生产入口测试后逐项替换,不能按字符串模式- 批量删除。+ 批量删除。后续识别 workspace cwd 后,逐项将这类混合文件改为真实回调、组件或脚本执行;+ 跨原生/JS、权限、凭证与竞态契约合并进已有 guard,纯布局字面量和已有真实覆盖的重复项才删除。- 最初迁移 27 个静态契约文件;审查恢复与扫描器补漏后,Desktop 和 Mobile 的跨文件安全、权限、主题或文案契约统一迁到各自 `guard` allowlist,由 CI 的 `pnpm test:guard` 执行。最终名单只在- `scripts/test-workspaces.config.mjs` 维护(Desktop 92、Mobile 29),由 runner 从 unit 排除;+ `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/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 7b562ffb32..048b16396f 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -1049,58 +1049,63 @@ describe('DeviceLinkClient', () => {});it('双方协商可靠传输后,大 invoke-result 分片并在累计 ACK 后停止重发', async () => {+ vi.useFakeTimers();const h = makeHarness({ timing: { pingIntervalMs: 10_000 } });- h.client.start();- await tick();- h.current().ack();+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(1);+ h.current().ack();- const open = h.client.openLink('dev-b', {- controllerName: 'Test',- protocolVersion: 1,- appVersion: '1',- });- const sentOpen = h.current().sent.find((e) => e.kind === 'link-open')!;- expect((sentOpen.payload as { capabilities: string[] }).capabilities).toContain(- DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,- );- h.current().push({- v: PROTOCOL_VERSION,- kind: 'link-accept',- id: sentOpen.id,- src: 'dev-b',- payload: {+ const open = h.client.openLink('dev-b', {+ controllerName: 'Test',+ protocolVersion: 1,appVersion: '1',- allowlistHash: 'hash',- capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],- },- });- await open;+ });+ const sentOpen = h.current().sent.find((e) => e.kind === 'link-open')!;+ expect((sentOpen.payload as { capabilities: string[] }).capabilities).toContain(+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,+ );+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'link-accept',+ id: sentOpen.id,+ src: 'dev-b',+ payload: {+ appVersion: '1',+ allowlistHash: 'hash',+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],+ },+ });+ await open;- const before = h.current().sent.length;- h.client.sendInvokeResult('dev-b', 'req-large', {- ok: true,- result: { text: '弱'.repeat(100_000) },- });- const chunks = h.current().sent.slice(before).filter((env) => env.kind === 'invoke-result');- expect(chunks.length).toBeGreaterThan(1);- const parsed = chunks.map((env) => parseTransportPayload(env.payload)!);- expect(parsed.map((part) => part.meta.segment!.index)).toEqual(- Array.from({ length: chunks.length }, (_, i) => i),- );- const { streamId, seq } = parsed[0].meta;- h.current().push({- v: PROTOCOL_VERSION,- kind: 'push',- src: 'dev-b',- payload: {- channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,- payload: { streamId, ackSeq: seq },- },- });- const afterAck = h.current().sent.length;- await tick(2_100);- expect(h.current().sent).toHaveLength(afterAck);- h.client.stop();+ const before = h.current().sent.length;+ h.client.sendInvokeResult('dev-b', 'req-large', {+ ok: true,+ result: { text: '弱'.repeat(100_000) },+ });+ const chunks = h.current().sent.slice(before).filter((env) => env.kind === 'invoke-result');+ expect(chunks.length).toBeGreaterThan(1);+ const parsed = chunks.map((env) => parseTransportPayload(env.payload)!);+ expect(parsed.map((part) => part.meta.segment!.index)).toEqual(+ Array.from({ length: chunks.length }, (_, i) => i),+ );+ const { streamId, seq } = parsed[0].meta;+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId, ackSeq: seq },+ },+ });+ const afterAck = h.current().sent.length;+ await vi.advanceTimersByTimeAsync(2_100);+ expect(h.current().sent).toHaveLength(afterAck);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }}, 5_000);it('累计 ACK 推进后不立即重发,定时重放时刷新 wrapper baseSeq', async () => {@@ -2504,6 +2509,7 @@ describe('DeviceLinkClient', () => {});it('已排期的通知重试在本地永久 closeLink 后被撤销,不补发迟到的 transport-timeout', async () => {+ vi.useFakeTimers();const h = makeHarness({timing: {pingIntervalMs: 60_000,@@ -2511,43 +2517,50 @@ describe('DeviceLinkClient', () => {transportMaxRetryAttempts: 2,},});- h.client.start();- await tick();- h.current().ack();- await establishInboundReliableLink(h, 'late-notify-local-close');+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(1);+ h.current().ack();+ const linked = establishInboundReliableLink(h, 'late-notify-local-close');+ await vi.advanceTimersByTimeAsync(1);+ await linked;- const socket = h.current();- h.client.sendInvokeResult('dev-b', 'late-1', { ok: true, result: [] });+ const socket = h.current();+ h.client.sendInvokeResult('dev-b', 'late-1', { ok: true, result: [] });- // 让 link-close 的首发持续失败 → 重试被排期- const originalSend = socket.send.bind(socket);- let blockedCloses = 0;- socket.send = (data: string) => {- const env = JSON.parse(data) as Envelope;- if (env.kind === 'link-close') {- blockedCloses += 1;- throw new Error('simulated backpressure');- }- originalSend(data);- };- await vi.waitFor(() => expect(blockedCloses).toBeGreaterThanOrEqual(1));+ // 让 link-close 的首发持续失败 → 重试被排期+ const originalSend = socket.send.bind(socket);+ let blockedCloses = 0;+ socket.send = (data: string) => {+ const env = JSON.parse(data) as Envelope;+ if (env.kind === 'link-close') {+ blockedCloses += 1;+ throw new Error('simulated backpressure');+ }+ originalSend(data);+ };+ await vi.waitFor(() => expect(blockedCloses).toBeGreaterThanOrEqual(1));- // 重试排期期间,本地永久关闭该链路(如用户断开/被控开关关闭)- socket.send = originalSend;- h.client.closeLink('dev-b', 'user');- const sentBefore = socket.sent.length;+ // 重试排期期间,本地永久关闭该链路(如用户断开/被控开关关闭)+ socket.send = originalSend;+ h.client.closeLink('dev-b', 'user');+ const sentBefore = socket.sent.length;- // 超过数个重试周期:不得再补发任何 transport-timeout- await tick(100);- const lateTimeouts = socket.sent.slice(sentBefore).filter((env) => (- env.kind === 'link-close'- && (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'- ));- expect(lateTimeouts).toHaveLength(0);- h.client.stop();+ // 超过数个重试周期:不得再补发任何 transport-timeout+ await vi.advanceTimersByTimeAsync(100);+ const lateTimeouts = socket.sent.slice(sentBefore).filter((env) => (+ env.kind === 'link-close'+ && (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'+ ));+ expect(lateTimeouts).toHaveLength(0);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }});it('收到对端永久 link-close 后,迟到的通知重试回调复验状态后终止,不补发 transport-timeout', async () => {+ vi.useFakeTimers();const h = makeHarness({timing: {pingIntervalMs: 60_000,@@ -2555,44 +2568,50 @@ describe('DeviceLinkClient', () => {transportMaxRetryAttempts: 3,},});- h.client.start();- await tick();- h.current().ack();- await establishInboundReliableLink(h, 'late-notify-peer-close');+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(1);+ h.current().ack();+ const linked = establishInboundReliableLink(h, 'late-notify-peer-close');+ await vi.advanceTimersByTimeAsync(1);+ await linked;- const socket = h.current();- h.client.sendInvokeResult('dev-b', 'late-2', { ok: true, result: [] });+ const socket = h.current();+ h.client.sendInvokeResult('dev-b', 'late-2', { ok: true, result: [] });- const originalSend = socket.send.bind(socket);- let blockedCloses = 0;- socket.send = (data: string) => {- const env = JSON.parse(data) as Envelope;- if (env.kind === 'link-close') {- blockedCloses += 1;- throw new Error('simulated backpressure');- }- originalSend(data);- };- await vi.waitFor(() => expect(blockedCloses).toBeGreaterThanOrEqual(1));+ const originalSend = socket.send.bind(socket);+ let blockedCloses = 0;+ socket.send = (data: string) => {+ const env = JSON.parse(data) as Envelope;+ if (env.kind === 'link-close') {+ blockedCloses += 1;+ throw new Error('simulated backpressure');+ }+ originalSend(data);+ };+ await vi.waitFor(() => expect(blockedCloses).toBeGreaterThanOrEqual(1));- // 重试排期期间收到对端的永久关闭(对方用户关掉了它对本机的控制)- socket.send = originalSend;- socket.push({- v: PROTOCOL_VERSION,- kind: 'link-close',- src: 'dev-b',- payload: { reason: 'user' },- });- await tick();- const sentBefore = socket.sent.length;+ // 重试排期期间收到对端的永久关闭(对方用户关掉了它对本机的控制)+ socket.send = originalSend;+ socket.push({+ v: PROTOCOL_VERSION,+ kind: 'link-close',+ src: 'dev-b',+ payload: { reason: 'user' },+ });+ await vi.advanceTimersByTimeAsync(1);+ const sentBefore = socket.sent.length;- await tick(150);- const lateTimeouts = socket.sent.slice(sentBefore).filter((env) => (- env.kind === 'link-close'- && (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'- ));- expect(lateTimeouts).toHaveLength(0);- h.client.stop();+ await vi.advanceTimersByTimeAsync(150);+ const lateTimeouts = socket.sent.slice(sentBefore).filter((env) => (+ env.kind === 'link-close'+ && (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'+ ));+ expect(lateTimeouts).toHaveLength(0);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }});it('入站方向被永久关闭后,出站重试耗尽不得再发 transport-timeout(不诱使对端重开用户已关闭的方向)', async () => {@@ -5937,31 +5956,38 @@ describe('DeviceLinkClient', () => {});it('可靠 invoke 分片在重组前也算入站活性', async () => {+ vi.useFakeTimers();const h = makeHarness({ timing: { pingIntervalMs: 50, pongMissLimit: 2 } });- h.client.start();- await tick();- h.current().ack();- await establishInboundReliableLink(h, 'heartbeat-fragment-stream');+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(1);+ h.current().ack();+ const linked = establishInboundReliableLink(h, 'heartbeat-fragment-stream');+ await vi.advanceTimersByTimeAsync(1);+ await linked;- const frames = encodeReliableFrames({- v: PROTOCOL_VERSION,- kind: 'invoke',- id: 'fragmented-heartbeat-invoke',- src: 'dev-b',- dst: 'dev-self',- payload: { channel: 'maker:large', args: ['x'.repeat(150_000)] },- }, 'heartbeat-fragment-stream', 1);- expect(frames.length).toBeGreaterThan(1);+ const frames = encodeReliableFrames({+ v: PROTOCOL_VERSION,+ kind: 'invoke',+ id: 'fragmented-heartbeat-invoke',+ src: 'dev-b',+ dst: 'dev-self',+ payload: { channel: 'maker:large', args: ['x'.repeat(150_000)] },+ }, 'heartbeat-fragment-stream', 1);+ expect(frames.length).toBeGreaterThan(1);- const activity = setInterval(() => {- for (const frame of frames) h.current().push(frame);- }, 10);- await tick(180);- clearInterval(activity);+ const activity = setInterval(() => {+ for (const frame of frames) h.current().push(frame);+ }, 10);+ await vi.advanceTimersByTimeAsync(180);+ clearInterval(activity);- expect(h.current().terminated).toBe(false);- expect(h.client.getStatus()).toBe('online');- h.client.stop();+ expect(h.current().terminated).toBe(false);+ expect(h.client.getStatus()).toBe('online');+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }});it('缺少 src 或 id 的可靠 invoke 不会喂活 heartbeat', async () => {diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjsindex 642350012d..f5a99de760 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -59,6 +59,19 @@ test("scanTestSource counts only unjustified hits for each rule", () => {["commented-out reset", "// vi.resetModules();", { resetModules: 0 }],["real 250ms wait", "await new Promise((r) => setTimeout(r, 250));", { realWaits: 1 }],["short wait", "await new Promise((r) => setTimeout(r, 20));", { realWaits: 0 }],+ ["local timeout wrapper", "const tick = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms)); await tick(2_100);", { realWaits: 1 }],+ ["constant timeout duration", "const SECOND = 1000; const timeout = 2 * SECOND; setTimeout(done, timeout);", { realWaits: 1 }],+ ["generic arrow in a ts file does not hide later waits", "const identity = <T>(value: T) => value; setTimeout(done, 200);", { realWaits: 1 }],+ ["property timeout keeps existing detection", "globalThis.setTimeout(done, 200);", { realWaits: 1 }],+ ["short wrapper and fixture shadow", "const tick = ms => new Promise(resolve => setTimeout(resolve, ms)); tick(20); function other(tick) { tick(500); }", { realWaits: 0 }],+ ["fake wrapper call", "const tick = ms => new Promise(resolve => setTimeout(resolve, ms)); it('fake', () => { vi.useFakeTimers(); tick(500); });", { realWaits: 0 }],+ ["an uncalled fake-timer helper does not hide real waits", "function enableFake() { vi.useFakeTimers(); } it('real', () => setTimeout(done, 200));", { realWaits: 1 }],+ ["an uncalled real-timer helper does not restore fake timers", "vi.useFakeTimers(); function cleanup() { vi.useRealTimers(); } it('fake', () => setTimeout(done, 200));", { realWaits: 0 }],+ ["a called fake-timer helper applies at the call site", "function enableFake() { vi.useFakeTimers(); } it('fake', () => { enableFake(); setTimeout(done, 200); });", { realWaits: 0 }],+ ["a called real-timer helper applies at the call site", "vi.useFakeTimers(); const cleanup = () => vi.useRealTimers(); it('real', () => { cleanup(); setTimeout(done, 200); });", { realWaits: 1 }],+ ["a registered timer helper applies as a hook", "function enableFake() { vi.useFakeTimers(); } beforeEach(enableFake); it('fake', () => setTimeout(done, 200));", { realWaits: 0 }],+ ["transitive timer helper calls preserve their order", "function fake() { vi.useFakeTimers(); } const setup = () => { fake(); vi.useRealTimers(); }; it('real', () => { setup(); setTimeout(done, 200); });", { realWaits: 1 }],+ ["inline Promise executors inherit test hooks", "beforeEach(() => vi.useFakeTimers()); it('fake', async () => { await new Promise(resolve => setTimeout(resolve, 200)); });", { realWaits: 0 }],["fake-timer file","vi.useFakeTimers();\nsetTimeout(tick, 5_000);",@@ -79,6 +92,8 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"vi.useFakeTimers(); afterEach(() => vi.useRealTimers()); it('first', () => {}); it('later', () => setTimeout(done, 100));",{ realWaits: 1 },],+ ["afterEach does not precede the first test", "vi.useFakeTimers(); afterEach(() => vi.useRealTimers()); it('first', () => setTimeout(done, 100));", { realWaits: 0 }],+ ["afterEach restores timers only for subsequent tests", "vi.useFakeTimers(); afterEach(() => vi.useRealTimers()); it('first', () => setTimeout(done, 100)); it('second', () => setTimeout(done, 100));", { realWaits: 1 }],["afterEach invalidates describe registration-time fake timers for later tests","describe('timers', () => { vi.useFakeTimers(); afterEach(() => vi.useRealTimers()); it('first', () => {}); it('later', () => setTimeout(done, 100)); });",@@ -94,6 +109,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"beforeEach(() => vi.useRealTimers()); describe('child', () => { beforeAll(() => vi.useFakeTimers()); it('real', () => setTimeout(done, 100)); });",{ realWaits: 1 },],+ [+ "global afterEach applies between sibling suites",+ "vi.useFakeTimers(); afterEach(() => vi.useRealTimers()); describe('one', () => { it('first', () => {}); }); describe('two', () => { it('second', () => setTimeout(done, 100)); });",+ { realWaits: 1 },+ ],+ [+ "new nested beforeAll runs after an earlier parent test",+ "afterEach(() => vi.useRealTimers()); it('parent', () => {}); describe('child', () => { beforeAll(() => vi.useFakeTimers()); it('first child', () => setTimeout(done, 100)); });",+ { realWaits: 0 },+ ],["multi-line real wait","await new Promise((resolve) => setTimeout(\n resolve,\n 250,\n));",@@ -129,6 +154,30 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"readFileSync(new URL('../data.json', import.meta.url)); readFileSync(new URL('../helper.bin', import.meta.url));",{ sourceReads: 0 },],+ ["workspace cwd source", "readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8');", { sourceReads: 1 }],+ ["cwd fixture stays test data", "readFileSync(resolve(process.cwd(), 'fixtures/helper.ts'), 'utf8');", { sourceReads: 0 }],+ ["executed source is a behavior harness", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); const run = new Function(source); expect(run()).toBe(true);", { sourceReads: 0 }],+ ["a local factory returns executed behavior", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); function make(code) { return new Function(code); } const run = make(source); expect(run()).toBe(true);", { sourceReads: 0 }],+ ["matchAll destructuring executes captured production code", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); const matches = [...source.matchAll(/return (.*);/g)]; for (const [, code] of matches) { const run = new Function(code); expect(run()).toBe(true); }", { sourceReads: 0 }],+ ["matchAll execution keeps a mixed text assertion", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); for (const [, code] of source.matchAll(/return (.*);/g)) { new Function(code)(); expect(code).toContain('true'); }", { sourceReads: 1 }],+ ["local geometry helpers return evaluated values rather than AST arguments", "const ast = ts.createSourceFile('x.ts', readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8')); function styles(file) { const value = new Function(file.getText())(); return Object.assign({}, value); } expect(styles(ast)).toEqual({ gap: 16 });", { sourceReads: 0 }],+ ["a factory with a raw text return branch stays a source assertion", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); function make(code, raw) { if (raw) return code; return new Function(code)(); } expect(make(source, true)).toContain('return true');", { sourceReads: 1 }],+ ["execution cannot exempt a mixed text assertion", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); expect(source).toContain('return true');", { sourceReads: 1 }],+ ["node assertion cannot be hidden by execution", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); assert.match(source, /return true/);", { sourceReads: 1 }],+ ["nested node assertion cannot be hidden by execution", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); assert.strict.match(source, /return true/);", { sourceReads: 1 }],+ ["unrelated execution does not exempt source text", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function('return true')(); expect(source).toContain('return true');", { sourceReads: 1 }],+ ["object property names do not alias a source binding", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); expect(render({ source: 'content' }).props).toEqual({ active: true });", { sourceReads: 0 }],+ ["member names do not alias a source binding", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); expect(result.source).toBe('content');", { sourceReads: 0 }],+ ["shorthand properties keep their source dependency", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); expect({ source }).toEqual({});", { sourceReads: 1 }],+ ["computed property names keep their source dependency", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); new Function(source)(); expect({ [source]: true }).toEqual({});", { sourceReads: 1 }],+ ["vm harness follows the actual read binding", "import vm from 'node:vm'; const sourcePath = resolve(process.cwd(), 'src/helper.ts'); const source = readFileSync(sourcePath, 'utf8'); vm.runInNewContext(source, context);", { sourceReads: 0 }],+ ["a vm namespace alias executes the actual read", "import * as evaluator from 'node:vm'; const vm = evaluator; const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); expect(vm.runInNewContext(source, context)).toBe(true);", { sourceReads: 0 }],+ ["a local vm object cannot exempt text assertions", "const vm = { runInNewContext: code => code }; const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); expect(vm.runInNewContext(source)).toContain('return true');", { sourceReads: 1 }],+ ["a local vm parameter shadows a real vm import", "import vm from 'node:vm'; const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); function check(vm) { expect(vm.runInNewContext(source)).toContain('return true'); } check({ runInNewContext: code => code });", { sourceReads: 1 }],+ ["named vm import executes the actual read", "import { runInNewContext as evaluate } from 'node:vm'; const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); expect(evaluate(source, context)).toBe(true);", { sourceReads: 0 }],+ ["a local vm-shaped helper cannot exempt text assertions", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); function runInNewContext(code) { return code; } expect(runInNewContext(source)).toContain('return true');", { sourceReads: 1 }],+ ["a shadowed Function cannot exempt text assertions", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); const Function = code => code; expect(new Function(source)).toContain('return true');", { sourceReads: 1 }],+ ["AST extraction executes the source callback", "const source = ts.createSourceFile('x.ts', readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8')); let expression; function visit(node) { expression = node.body; } visit(source); const compiled = ts.transpileModule(expression.getText(source)).outputText; const run = new Function(compiled); expect(run()).toBe(true);", { sourceReads: 0 }],["multi-line source path declared before the read","const sourcePath = resolve(\n __dirname,\n '..',\n 'Image.tsx',\n);\nconst source = readFileSync(sourcePath, 'utf8');",diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 889d10dd8d..9c356b6de2 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -46,6 +46,7 @@ import {printSummary,readAllFiles,resolveOutputStream,+ resolveTestInvocation,runCommand,runPlannedTests,runWithExclusiveBarriers,@@ -2069,14 +2070,14 @@ test("runPlannedTests passes selected include files to packageBin commands", asyreturn { exitCode: 0, output: "PASS" };},});- // Windows 上 resolvePnpmInvocation 会通过 cmd.exe 包装,实际 pnpm 参数- // 放在 env 的 CINDY_PNPM_CMD_ARG_N 里。其他平台参数直接在 args 里。+ // Non-Vitest wrappers may carry arguments through cmd environment slots;+ // directly launched Vitest keeps them in the argv array on every platform.const call = calls[0];- const pnpmArgs = call.options?.env- ? Object.keys(call.options.env)- .filter((k) => k.startsWith("CINDY_PNPM_CMD_ARG_"))- .sort()- .map((k) => call.options.env[k])+ const cmdEnvKeys = Object.keys(call.options?.env ?? {})+ .filter((k) => k.startsWith("CINDY_PNPM_CMD_ARG_"))+ .sort();+ const pnpmArgs = cmdEnvKeys.length+ ? cmdEnvKeys.map((k) => call.options.env[k]): call.args;assert.deepEqual(pnpmArgs.slice(-1), ["src/__tests__/orca-bridge-mcp.test.ts",@@ -2098,6 +2099,56 @@ test("buildPnpmArgs rejects selected files outside the workspace", () => {);});+// PR #6196: the guard exclusion list crossed cmd.exe's 8191-character limit+// inside pnpm exec on Windows. Exercise the real runner and a small existing+// suite; nonmatching exclusions reproduce the launch failure without changing+// test selection or creating another Vitest harness.+test("Windows long Vitest arguments reach the test process without cmd truncation", async () => {+ const values = ["a space", "中文", 'a"quote', "%TEMP%", "a&b", "a^b", "long-".repeat(1800)];+ const echoArgs = ["--dir", ROOT, "exec", "vitest", "process.stdout.write(JSON.stringify(process.argv.slice(1)))", "--", ...values];+ const options = { platform: "win32", execPath: process.execPath, vitestEntry: "-e", env: { ...process.env, Path: "original-path", PATH: "duplicate-path" } };+ for (const npmExecPath of [undefined, "pnpm.cmd"]) {+ const invocation = resolveTestInvocation(echoArgs, { ...options, npmExecPath });+ assert.equal(invocation.command, process.execPath);+ assert.equal(invocation.shell, false);+ assert.equal(Object.keys(invocation.env).filter((key) => key.toLowerCase() === "path").length, 1);+ const echoed = await runCommand(invocation.command, invocation.args, { env: invocation.env, shell: false, stdout: null, stderr: null });+ assert.equal(echoed.exitCode, 0, echoed.output);+ assert.deepEqual(JSON.parse(echoed.output), values);+ }+ for (const [args, platform] of [[echoArgs, "linux"], [["--dir", ROOT, "run", "test"], "win32"], [["--dir", ROOT, "exec", "other-tool"], "win32"]]) {+ const fallbackOptions = { platform, npmExecPath: "/tools/pnpm.cjs", execPath: process.execPath };+ assert.deepEqual(resolveTestInvocation(args, fallbackOptions), resolvePnpmInvocation(args, fallbackOptions));+ }+ const file = "src/main/agent-island/__tests__/nativeContracts.test.ts";+ const workspace = {+ name: "desktop",+ cwd: "apps/desktop",+ status: "required",+ tiers: {+ guard: {+ status: "required",+ coverage: "allowlist",+ command: { type: "packageBin", bin: "vitest", args: ["run", "--pool=forks", "--maxWorkers=1"] },+ include: [file],+ exclude: Array.from({ length: 90 }, (_, i) => "src/never-selected/" + "long-path-".repeat(10) + i + ".test.ts"),+ },+ },+ };+ const files = ["apps/desktop/" + file];+ const pnpmArgs = buildPnpmArgs(ROOT, workspace, workspace.tiers.guard.command, workspace.tiers.guard, files);+ assert.ok(pnpmArgs.join(" ").length > 8191);+ const [result] = await runPlannedTests({+ root: ROOT,+ workspaceCwds: [workspace.cwd],+ manifest: { workspaces: [workspace] },+ allFiles: files,+ tier: "guard",+ });+ assert.equal(result.exitCode, 0, result.output);+ assert.match(result.output, /nativeContracts\.test\.ts/);+});+test("buildPnpmArgs switches vitest to related mode when related files are provided", () => {const args = buildPnpmArgs("F:/repo",diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex 3143985ea2..cb8d69f9ce 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -33,12 +33,19 @@ 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 = /\b(?:sleep|delay|wait|waitMs|pause)\s*\(\s*(\d[\d_]*)\s*\)/g;+const REAL_WAIT_NAMES = new Set(['sleep', 'delay', 'wait', 'waitMs', 'pause']);// Reuse Desktop's declared parser to locate test/hook callbacks and local helpers.// No type checking or module loading is needed.const requireDesktop = createRequire(new URL('../apps/desktop/package.json', import.meta.url));let typescript;+function parseTestSource(ts, code) {+ const tsx = ts.createSourceFile('test.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ if (tsx.parseDiagnostics.length === 0) return tsx;+ const plain = ts.createSourceFile('test.ts', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ return plain.parseDiagnostics.length < tsx.parseDiagnostics.length ? plain : tsx;+}+/** Replace comments with spaces (keeping newlines) so matches ignore commented-out code. */export function stripComments(source) {let out = '';@@ -95,7 +102,7 @@ function countModuleResets(code, lines) {const resets = [...code.matchAll(/\bvi\.resetModules\s*\(/g)];if (resets.length === 0) return 0;const ts = typescript ??= requireDesktop('typescript');- const source = ts.createSourceFile('test.tsx', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);+ const source = parseTestSource(ts, code);const nodeScopes = new WeakMap();const hooks = [];const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);@@ -186,72 +193,191 @@ function maskStrings(source) {return out;}-function setTimeoutCalls(code) {+function staticWaitCalls(code) {+ if (!/\b(?:setTimeout|sleep|delay|wait|waitMs|pause)\s*\(/.test(code)) return [];+ const ts = typescript ??= requireDesktop('typescript');+ const source = parseTestSource(ts, code);+ const nodeScopes = new WeakMap();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;+ const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);+ function collect(node, scope) {+ if (ts.isFunctionDeclaration(node) && node.name) scope.bindings.set(node.name.text, node);+ if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node)) scope = { parent: scope, bindings: new Map() };+ nodeScopes.set(node, scope);+ if (isFunction(node)) {+ for (const parameter of node.parameters) {+ if (ts.isIdentifier(parameter.name)) scope.bindings.set(parameter.name.text, parameter);}- 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 });+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) scope.bindings.set(node.name.text, node);+ if (ts.isCallExpression(node)) calls.push(node);+ ts.forEachChild(node, child => collect(child, scope));}- return calls;+ collect(source, null);+ function binding(identifier) {+ for (let scope = nodeScopes.get(identifier); scope; scope = scope.parent) {+ if (scope.bindings.has(identifier.text)) return scope.bindings.get(identifier.text);+ }+ return null;+ }+ function number(node, parameters = new Map(), seen = new Set()) {+ if (!node || seen.has(node)) return undefined;+ seen = new Set(seen).add(node);+ if (ts.isNumericLiteral(node)) return Number(node.text.replaceAll('_', ''));+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node)) return number(node.expression, parameters, seen);+ if (ts.isIdentifier(node)) {+ const bound = binding(node);+ if (!bound) return undefined;+ if (parameters.has(bound)) return parameters.get(bound);+ if (ts.isVariableDeclaration(bound) && (bound.parent.flags & ts.NodeFlags.Const)) return number(bound.initializer, parameters, seen);+ return undefined;+ }+ if (ts.isPrefixUnaryExpression(node)) {+ const value = number(node.operand, parameters, seen);+ if (node.operator === ts.SyntaxKind.MinusToken) return -value;+ if (node.operator === ts.SyntaxKind.PlusToken) return value;+ }+ if (ts.isBinaryExpression(node)) {+ const left = number(node.left, parameters, seen);+ const right = number(node.right, parameters, seen);+ if (left === undefined || right === undefined) return undefined;+ switch (node.operatorToken.kind) {+ case ts.SyntaxKind.PlusToken: return left + right;+ case ts.SyntaxKind.MinusToken: return left - right;+ case ts.SyntaxKind.AsteriskToken: return left * right;+ case ts.SyntaxKind.SlashToken: return left / right;+ }+ }+ return undefined;+ }+ // Recognize direct local wrappers returning a timeout or Promise containing+ // one. Do not follow arbitrary control flow, callbacks or external helpers.+ function wrapperTimer(fn) {+ if (!fn?.body) return null;+ const body = ts.isBlock(fn.body)+ ? fn.body.statements.find(ts.isReturnStatement)?.expression : fn.body;+ if (!body) return null;+ if (ts.isCallExpression(body) && body.expression.getText(source) === 'setTimeout') return body;+ if (!ts.isNewExpression(body) || body.expression.getText(source) !== 'Promise') return null;+ const executor = body.arguments?.[0];+ if (!executor || !isFunction(executor)) return null;+ const candidates = ts.isBlock(executor.body) ? executor.body.statements.map(statement => statement.expression) : [executor.body];+ return candidates.find(node => node && ts.isCallExpression(node) && node.expression.getText(source) === 'setTimeout') ?? null;+ }+ const waits = [];+ for (const call of calls) {+ const name = ts.isIdentifier(call.expression) ? call.expression.text+ : ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : '';+ let duration;+ if (name === 'setTimeout') duration = number(call.arguments[1]);+ else if (REAL_WAIT_NAMES.has(name)) duration = number(call.arguments[0]);+ else {+ if (!ts.isIdentifier(call.expression)) continue;+ const bound = binding(call.expression);+ const fn = bound && ts.isVariableDeclaration(bound) ? bound.initializer : bound;+ if (!fn || !isFunction(fn)) continue;+ const timer = wrapperTimer(fn);+ if (!timer) continue;+ const parameters = new Map(fn.parameters.map((parameter, index) => [parameter, number(call.arguments[index] ?? parameter.initializer)]));+ // Constant waits inside a helper are already counted at their own site.+ if (number(timer.arguments[1]) !== undefined) continue;+ duration = number(timer.arguments[1], parameters);+ }+ if (Number.isFinite(duration)) waits.push({ index: call.getStart(source), duration });+ }+ return waits;}-function timerScopes(code) {+function timerScopes(code, timerEvents) {const ts = typescript ??= requireDesktop('typescript');- const source = ts.createSourceFile('test.tsx', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);+ const source = parseTestSource(ts, code);const scopes = [];+ const nodeScopes = new WeakMap();+ const callbackKinds = new WeakMap();+ const registeredHelpers = [];+ const calls = [];+ const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);function rootName(expression) {if (ts.isIdentifier(expression)) return expression.text;if (ts.isPropertyAccessExpression(expression) || ts.isCallExpression(expression)) return rootName(expression.expression);if (ts.isTaggedTemplateExpression(expression)) return rootName(expression.tag);return '';}- function visit(node) {+ function visit(node, lexicalScope) {+ if (ts.isFunctionDeclaration(node) && node.name) lexicalScope.bindings.set(node.name.text, node);+ if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node)) lexicalScope = { parent: lexicalScope, bindings: new Map() };+ nodeScopes.set(node, lexicalScope);+ if (isFunction(node)) {+ scopes.push({ kind: callbackKinds.get(node) ?? 'helper', start: node.getStart(source), end: node.end });+ for (const parameter of node.parameters) {+ if (ts.isIdentifier(parameter.name)) lexicalScope.bindings.set(parameter.name.text, null);+ }+ }+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) lexicalScope.bindings.set(node.name.text, node.initializer && isFunction(node.initializer) ? node.initializer : null);if (ts.isCallExpression(node)) {+ calls.push(node);const kind = rootName(node.expression);if (/^(?:describe|it|test|beforeEach|beforeAll|afterEach|afterAll)$/.test(kind)) {for (const argument of node.arguments) {- if (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)) {- scopes.push({ kind, start: argument.getStart(source), end: argument.end });+ if (isFunction(argument)) callbackKinds.set(argument, kind);+ else if (ts.isIdentifier(argument)) {+ const scope = { kind, start: argument.getStart(source), end: argument.end };+ scopes.push(scope);+ registeredHelpers.push({ argument, scope });}}}}- ts.forEachChild(node, visit);+ ts.forEachChild(node, child => visit(child, lexicalScope));+ }+ visit(source, null);+ scopes.sort((a, b) => (a.end - a.start) - (b.end - b.start));+ function helper(expression) {+ if (isFunction(expression)) return expression;+ if (!ts.isIdentifier(expression)) return null;+ for (let scope = nodeScopes.get(expression); scope; scope = scope.parent) {+ if (scope.bindings.has(expression.text)) return scope.bindings.get(expression.text);+ }+ return null;+ }+ function helperEvents(fn, seen = new Set()) {+ if (!fn?.body || seen.has(fn)) return [];+ seen = new Set(seen).add(fn);+ const events = [];+ function inspect(node) {+ if (isFunction(node)) return;+ if (ts.isCallExpression(node)) {+ const expression = node.expression;+ if (ts.isPropertyAccessExpression(expression) && expression.expression.getText(source) === 'vi'+ && /^(?:useFakeTimers|useRealTimers)$/.test(expression.name.text)) events.push(expression.name.text);+ else events.push(...helperEvents(helper(expression), seen));+ }+ ts.forEachChild(node, inspect);+ }+ inspect(fn.body);+ return events;+ }+ function addEvents(names, index) {+ names.forEach((name, order) => timerEvents.push({ 1: name, index: index + (order + 1) / 1e6 }));+ }+ // A helper definition does not change timer mode. Apply its reachable timer+ // calls only where it is actually invoked or registered as a framework hook.+ for (const call of calls) {+ const index = call.getStart(source);+ if (scopes.find(scope => scope.start <= index && index < scope.end)?.kind === 'helper') continue;+ addEvents(helperEvents(helper(call.expression)), index);}- visit(source);- return scopes.sort((a, b) => (a.end - a.start) - (b.end - b.start));+ for (const { argument, scope } of registeredHelpers) addEvents(helperEvents(helper(argument)), scope.start);+ timerEvents.sort((a, b) => a.index - b.index);+ return scopes;}function timerStateAt(index, timerEvents, scopes) {const scopeAt = (position) => scopes.find(s => s.start <= position && position < s.end);- const waitScope = scopeAt(index);+ const localWaitScope = scopeAt(index);+ // Inline executors (for example a Promise around setTimeout) still run in+ // the surrounding test and inherit its hooks, unlike an uncalled definition.+ const waitScope = scopes.find(s => s.kind !== 'helper' && s.start <= index && index < s.end) ?? localWaitScope;const describeAt = (scope) => scopes.find(s => s.kind === 'describe' && s.start < scope.start && scope.end < s.end);const belongsToWait = (scope) => !scope || scope.kind === 'describe' && scope.start < index && index < scope.end;const events = timerEvents.map(event => ({ event, scope: scopeAt(event.index) }));@@ -263,7 +389,13 @@ function timerStateAt(index, timerEvents, scopes) {if (waitScope && /^(?:it|test)$/.test(waitScope.kind)) {// Registration-time setup, like beforeAll, runs only once. An afterEach// restoring real timers can invalidate it before a later test runs.- const restoresRealTimers = events.some(entry => entry.scope?.kind === 'afterEach' && entry.event[1] === 'useRealTimers' && belongsToWait(describeAt(entry.scope)));+ const earlierTests = scopes.filter(scope => /^(?:it|test)$/.test(scope.kind) && scope.end < waitScope.start);+ const containsTest = (suite, test) => !suite || suite.start < test.start && test.end < suite.end;+ const restoringHooks = events.filter(entry => entry.scope?.kind === 'afterEach'+ && entry.event[1] === 'useRealTimers' && belongsToWait(describeAt(entry.scope)));+ const hasRestoredTimers = (suite) => restoringHooks.some(entry => earlierTests.some(test =>+ containsTest(suite, test) && containsTest(describeAt(entry.scope), test)));+ const restoresRealTimers = hasRestoredTimers(null);if (restoresRealTimers) fake = false;const hooks = events.filter(({ scope }) => scope && /^(?:beforeAll|beforeEach)$/.test(scope.kind) && belongsToWait(describeAt(scope))).sort((a, b) => {@@ -275,30 +407,24 @@ function timerStateAt(index, timerEvents, scopes) {for (const { event, scope } of hooks) {// An afterEach restoring real timers invalidates beforeAll-only setup// for subsequent tests. Be conservative rather than exempt a real wait.- if (scope.kind === 'beforeAll' && restoresRealTimers) continue;+ if (scope.kind === 'beforeAll' && hasRestoredTimers(describeAt(scope))) continue;fake = event[1] === 'useFakeTimers';}}for (const { event, scope } of events) {- if (scope === waitScope && event.index < index) fake = event[1] === 'useFakeTimers';+ if ((scope === waitScope || scope === localWaitScope) && event.index < index) fake = event[1] === 'useFakeTimers';}return fake;}function countRealWaits(code, lines) {const timerEvents = [...code.matchAll(/\bvi\.(useFakeTimers|useRealTimers)\s*\(/g)];- const scopes = timerEvents.length > 0 ? timerScopes(code) : [];+ const scopes = timerEvents.length > 0 ? timerScopes(code, timerEvents) : [];let count = 0;- 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);+ const waits = staticWaitCalls(code).sort((a, b) => a.index - b.index);for (const wait of waits) {if (timerStateAt(wait.index, timerEvents, scopes)) continue;- if (Number(wait.duration.replaceAll('_', '')) < REAL_WAIT_MIN_MS) continue;+ if (wait.duration < REAL_WAIT_MIN_MS) continue;const line = lineOf(code, wait.index);if (!hasJustification(lines, line, 'real-wait')) count += 1;}@@ -311,7 +437,7 @@ const SOURCE_EXT = new RegExp('\\.' + SOURCE_EXTENSION + '$', 'i');const SOURCE_LITERAL = new RegExp('\\.' + SOURCE_EXTENSION + '[\'"]', 'i');// Only anchors that point into the checkout count; generic names such as `root`// usually hold an mkdtemp() directory whose fake source files are test input.-const REPO_ANCHOR = /__dirname|import\.meta\.(?:url|dirname)|\b(?:REPO_ROOT|repoRoot|desktopRoot)\b/;+const REPO_ANCHOR = /__dirname|import\.meta\.(?:url|dirname)|process\.cwd\s*\(\s*\)|\b(?:REPO_ROOT|repoRoot|desktopRoot)\b/;function findEnclosingReadCall(code, index, pattern = /\breadFile(?:Sync)?\s*\(/g) {const starts = [...code.matchAll(pattern)];@@ -391,6 +517,187 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {return callStart >= 0 && (value.startsWith('./') || value.startsWith('../'));}+/** Source compiled and executed by a behavior harness is not a text assertion.+ * Follow each read's local bindings to execution and assertion sites separately:+ * an unrelated new Function must never exempt a source-literal assertion.+ */+function executedSourcePaths(code) {+ const ts = typescript ??= requireDesktop('typescript');+ const source = parseTestSource(ts, code);+ const scopes = new WeakMap();+ const reads = [];+ const calls = [];+ const strings = [];+ const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);+ function collect(node, scope) {+ if (ts.isFunctionDeclaration(node) && node.name) scope.bindings.set(node.name.text, node);+ if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node) || ts.isForOfStatement(node)) scope = { parent: scope, bindings: new Map() };+ scopes.set(node, scope);+ if (isFunction(node)) for (const parameter of node.parameters) {+ if (ts.isIdentifier(parameter.name)) scope.bindings.set(parameter.name.text, parameter);+ }+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) scope.bindings.set(node.name.text, node);+ if (ts.isVariableDeclaration(node) && ts.isArrayBindingPattern(node.name)) {+ const loop = node.parent.parent;+ if (ts.isForOfStatement(loop)) {+ for (const element of node.name.elements) {+ if (ts.isBindingElement(element) && ts.isIdentifier(element.name)) scope.bindings.set(element.name.text, element);+ }+ }+ }+ if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node) && node.name) scope.bindings.set(node.name.text, node);+ if (ts.isStringLiteralLike(node)) strings.push(node);+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {+ calls.push(node);+ const name = ts.isIdentifier(node.expression) ? node.expression.text+ : ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : '';+ if (name === 'readFileSync' || name === 'readFile') reads.push(node);+ }+ ts.forEachChild(node, child => collect(child, scope));+ }+ collect(source, null);+ function binding(identifier) {+ for (let scope = scopes.get(identifier); scope; scope = scope.parent) {+ if (scope.bindings.has(identifier.text)) return scope.bindings.get(identifier.text);+ }+ return null;+ }+ function vmNamespace(node, seen = new Set()) {+ if (!ts.isIdentifier(node) || seen.has(node)) return false;+ seen.add(node);+ const bound = binding(node);+ if (bound && ts.isVariableDeclaration(bound) && bound.initializer) return vmNamespace(bound.initializer, seen);+ const declaration = bound && (ts.isNamespaceImport(bound) ? bound.parent.parent+ : ts.isImportClause(bound) ? bound.parent : null);+ return declaration && ts.isImportDeclaration(declaration) && ts.isStringLiteral(declaration.moduleSpecifier)+ && /^(?:node:)?vm$/.test(declaration.moduleSpecifier.text);+ }+ function execution(node) {+ if (!ts.isNewExpression(node) && !ts.isCallExpression(node)) return false;+ if (ts.isPropertyAccessExpression(node.expression)) return /^runIn(?:New)?Context$/.test(node.expression.name.text)+ && vmNamespace(node.expression.expression);+ if (!ts.isIdentifier(node.expression)) return false;+ const bound = binding(node.expression);+ if (!bound) return node.expression.text === 'Function';+ if (!ts.isImportSpecifier(bound)) return false;+ const imported = bound.propertyName?.text ?? bound.name.text;+ const declaration = bound.parent.parent.parent;+ return /^runIn(?:New)?Context$/.test(imported) && ts.isImportDeclaration(declaration)+ && ts.isStringLiteral(declaration.moduleSpecifier) && /^(?:node:)?vm$/.test(declaration.moduleSpecifier.text);+ }+ const writes = new Map();+ function addWrite(bound, value) {+ if (bound && value) writes.set(bound, [...(writes.get(bound) ?? []), value]);+ }+ function collectWrites(node) {+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isIdentifier(node.left)) {+ addWrite(binding(node.left), node.right);+ }+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {+ const bound = binding(node.expression);+ const fn = bound && ts.isVariableDeclaration(bound) ? bound.initializer : bound;+ if (fn && isFunction(fn)) fn.parameters.forEach((parameter, index) => addWrite(parameter, node.arguments[index]));+ }+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)+ && /^(?:set|push|unshift|add)$/.test(node.expression.name.text) && ts.isIdentifier(node.expression.expression)) {+ for (const argument of node.arguments) addWrite(binding(node.expression.expression), argument);+ }+ ts.forEachChild(node, collectWrites);+ }+ collectWrites(source);+ const returnCache = new WeakMap();+ function returns(fn) {+ if (returnCache.has(fn)) return returnCache.get(fn);+ if (!fn.body) return [];+ if (!ts.isBlock(fn.body)) return [fn.body];+ const result = [];+ function visit(node) {+ if (isFunction(node)) return;+ if (ts.isReturnStatement(node) && node.expression) result.push(node.expression);+ ts.forEachChild(node, visit);+ }+ visit(fn.body);+ returnCache.set(fn, result);+ return result;+ }+ const readSet = new Set(reads);+ function dependencies(node, seen = new Set(), paths = false) {+ if (!node || seen.has(node)) return new Set();+ seen.add(node);+ if (paths && ts.isStringLiteralLike(node)) return new Set([node.getStart(source)]);+ if (!paths && readSet.has(node)) return new Set([node]);+ if (isFunction(node)) {+ const result = new Set();+ for (const value of returns(node)) for (const dependency of dependencies(value, seen, paths)) result.add(dependency);+ return result;+ }+ if (ts.isIdentifier(node)) {+ // A property label is not a read of a same-named local source variable.+ // Shorthand and computed properties are expressions and still propagate.+ if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node+ || ts.isPropertyAssignment(node.parent) && node.parent.name === node) return new Set();+ const bound = binding(node);+ const values = [...(writes.get(bound) ?? [])];+ if (bound && (ts.isVariableDeclaration(bound) || ts.isParameter(bound))) values.push(bound.initializer);+ if (bound && ts.isBindingElement(bound)) values.push(bound.parent.parent.parent.parent.expression);+ if (bound && isFunction(bound)) values.push(...returns(bound));+ const result = new Set();+ for (const value of values) for (const dependency of dependencies(value, seen, paths)) result.add(dependency);+ return result;+ }+ // Once the compiled function is invoked, its return value is behavior, not+ // source text. Its code input is inspected independently at the sink below.+ if (!paths && (ts.isCallExpression(node) || ts.isNewExpression(node)) && execution(node)) return new Set();+ if (ts.isCallExpression(node)) {+ const callee = ts.isIdentifier(node.expression) ? binding(node.expression) : null;+ const fn = callee && ts.isVariableDeclaration(callee) ? callee.initializer : callee;+ if (fn && isFunction(fn)) {+ // Parameters already carry their actual writes. A local helper's+ // output depends on its returns, not every unrelated input argument.+ const result = new Set();+ for (const value of returns(fn)) for (const dependency of dependencies(value, seen, paths)) result.add(dependency);+ return result;+ }+ const initializer = callee && ts.isVariableDeclaration(callee) ? callee.initializer : node.expression;+ if (!paths && initializer && execution(initializer)) return new Set();+ }+ const result = new Set();+ ts.forEachChild(node, child => {+ for (const dependency of dependencies(child, seen, paths)) result.add(dependency);+ });+ return result;+ }+ const executed = new Set();+ const asserted = new Set();+ for (const call of calls) {+ if (execution(call)) {+ for (const argument of call.arguments ?? []) for (const read of dependencies(argument)) executed.add(read);+ if (ts.isPropertyAccessExpression(call.expression)) {+ for (const read of dependencies(call.expression.expression)) executed.add(read);+ }+ }+ let assertionExpression = call.expression;+ while (ts.isPropertyAccessExpression(assertionExpression)) assertionExpression = assertionExpression.expression;+ const assertion = ts.isIdentifier(assertionExpression) ? assertionExpression.text : '';+ if (/^(?:expect|expectTypeOf|assert)$/.test(assertion)) {+ for (const argument of call.arguments ?? []) for (const read of dependencies(argument)) asserted.add(read);+ }+ }+ const exempt = new Set();+ const readHelpers = findSourceReadHelpers(code);+ for (const read of executed) {+ if (asserted.has(read)) continue;+ for (const position of dependencies(read.arguments[0], new Set(), true)) exempt.add(position);+ // readSource('../x.ts') helpers keep their path at the call site. Only+ // calls whose result actually depends on this executed read qualify.+ for (const call of calls) {+ if (!ts.isIdentifier(call.expression) || !readHelpers.has(call.expression.text) || !dependencies(call).has(read)) continue;+ for (const argument of call.arguments ?? []) for (const position of dependencies(argument, new Set(), true)) exempt.add(position);+ }+ }+ return exempt;+}+/** Count unjustified rule hits in one unit test file. */export function scanTestSource(source, { isGuard = false } = {}) {const code = stripComments(source);@@ -401,7 +708,9 @@ export function scanTestSource(source, { isGuard = false } = {}) {let sourceReads = 0;if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw/.test(code)) {const sourceReadHelpers = findSourceReadHelpers(code);+ const executablePaths = /\bFunction\b|\brunIn(?:New)?Context\b/.test(code) ? executedSourcePaths(code) : new Set();for (const match of code.matchAll(/(['"`])([^'"`\n$]+)\1/g)) {+ if (executablePaths.has(match.index)) continue;if (match[2].endsWith('?raw') || isSourcePathLiteral(code, match, sourceReadHelpers)) sourceReads += 1;}}diff --git a/scripts/desktop-worker-benchmark.mjs b/scripts/desktop-worker-benchmark.mjsindex cf65e84205..2465b1298c 100644--- a/scripts/desktop-worker-benchmark.mjs+++ b/scripts/desktop-worker-benchmark.mjs@@ -6,10 +6,10 @@ import { performance } from 'node:perf_hooks';import { fileURLToPath } from 'node:url';import manifest from './test-workspaces.config.mjs';-import { resolvePnpmInvocation } from './shared/pnpm-invocation.mjs';import {buildPnpmArgs,normalizeRelPath,+ resolveTestInvocation,runCommand,} from './test-workspaces.mjs';@@ -182,7 +182,7 @@ async function runSample({ workers, iteration, top }) {`cindy-desktop-worker-benchmark-${process.pid}-${workers}-${iteration}.json`,);const { cwd, pnpmArgs } = desktopUnitCommand(workers, outputFile);- const invocation = resolvePnpmInvocation(pnpmArgs);+ const invocation = resolveTestInvocation(pnpmArgs);const startedAt = performance.now();try {const result = await runCommand(invocation.command, invocation.args, {diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex f9608314f7..098fe67142 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -4,9 +4,6 @@"apps/desktop/scripts/nsis-include-paths.test.mjs": {"sourceReads": 1},- "apps/desktop/scripts/render-recovery/main.test.mjs": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/accessibilitySupportIpc.test.ts": {"resetModules": 1},@@ -28,27 +25,15 @@"apps/desktop/src/main/__tests__/authAccountsIpcSecurity.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/__tests__/authLoginBack.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/__tests__/authPostCommitStartup.test.ts": {- "sourceReads": 2- },"apps/desktop/src/main/__tests__/cdnResponseLifecycle.test.ts": {"resetModules": 1},"apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/__tests__/cindyMakeGithubIpc.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.ts": {"sourceReads": 1},@@ -113,18 +98,12 @@"apps/desktop/src/main/__tests__/notificationService.test.ts": {"resetModules": 1},- "apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/projectOrderStore.test.ts": {"resetModules": 1},"apps/desktop/src/main/__tests__/providerImportWiring.test.ts": {"sourceReads": 5},- "apps/desktop/src/main/__tests__/queuedMessageTrustBoundary.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/releaseNotesService.test.ts": {"resetModules": 1},@@ -134,9 +113,6 @@"apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts": {"resetModules": 1},@@ -152,14 +128,11 @@"apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts": {"resetModules": 1},- "apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/updateChannelStore.test.ts": {"resetModules": 1},"apps/desktop/src/main/__tests__/updaterUi.test.ts": {- "sourceReads": 4+ "sourceReads": 1},"apps/desktop/src/main/__tests__/updateService.test.ts": {"resetModules": 1@@ -256,15 +229,9 @@"apps/desktop/src/main/device-link/__tests__/deviceName.test.ts": {"resetModules": 1},- "apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts": {- "sourceReads": 2- },"apps/desktop/src/main/device-link/__tests__/providerShareGuestPrefs.test.ts": {"resetModules": 1},- "apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts": {"sourceReads": 1},@@ -280,9 +247,6 @@"apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts": {"realWaits": 3},- "apps/desktop/src/main/goal-host/__tests__/controller.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/localDb/__tests__/cjkSeg.test.ts": {"sourceReads": 1},@@ -299,7 +263,7 @@"sourceReads": 1},"apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts": {"sourceReads": 1@@ -316,9 +280,6 @@"apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts": {"sourceReads": 1},@@ -328,9 +289,6 @@"apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts": {"resetModules": 1},- "apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts": {"resetModules": 17},@@ -359,16 +317,13 @@"sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts": {- "sourceReads": 3+ "sourceReads": 2},"apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.ts": {- "sourceReads": 3+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts": {"resetModules": 1@@ -376,32 +331,17 @@"apps/desktop/src/main/maker-ipc/__tests__/botTaskCoordination.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibilityAuthority.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/chatInviteRevokeIpcSecurity.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/cindyMakeFeatureGate.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/llamaCppContextOwner.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts": {"sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts": {"sourceReads": 1@@ -409,78 +349,33 @@"apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts": {"sourceReads": 2},- "apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts": {- "sourceReads": 2- },- "apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts": {- "sourceReads": 2- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts": {- "sourceReads": 2- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts": {+ "apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts": {"sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts": {- "sourceReads": 4- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts": {- "sourceReads": 3- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerDirectoryWindows.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccessHost.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/promptPredictionStopLedger.test.ts": {"sourceReads": 2},"apps/desktop/src/main/maker-ipc/__tests__/schedulerQueuedPreparation.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/maker-ipc/__tests__/sessionQueueControl.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/maker-ipc/__tests__/silentStopContinuationBinding.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/mcp-integrations/__tests__/botTaskCreationResponsibility.test.ts": {- "sourceReads": 2- },"apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.ts": {"sourceReads": 3},- "apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/mcp-integrations/__tests__/schedulerDevices.test.ts": {"sourceReads": 2},"apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts": {"sourceReads": 1},@@ -508,15 +403,6 @@"apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts": {"sourceReads": 3},- "apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/main/remote-desktop/__tests__/linuxPackaging.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts": {"resetModules": 1},@@ -529,15 +415,9 @@"apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts": {"resetModules": 1},- "apps/desktop/src/main/remote-ssh/__tests__/remoteAgentReadiness.test.ts": {- "sourceReads": 2- },"apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/remote-ssh/__tests__/silentInstallStatus.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/resource-usage-window/__tests__/windowSecurity.test.ts": {"sourceReads": 4},@@ -625,12 +505,6 @@"apps/desktop/src/preload/__tests__/browserCommentPreload.test.ts": {"resetModules": 1},- "apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/preload/__tests__/ghostInspectTarget.test.ts": {- "sourceReads": 1- },"apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts": {"sourceReads": 1},@@ -653,7 +527,7 @@"sourceReads": 2},"apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts": {- "sourceReads": 4+ "sourceReads": 3},"apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts": {"sourceReads": 1@@ -727,12 +601,6 @@"apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/__tests__/focusScrollSettlement.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/focusScrollWindow.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/foregroundRecoveryDiagnostics.test.ts": {"sourceReads": 1},@@ -763,21 +631,9 @@"apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/__tests__/historyPrefetch.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/historyTurnChangesProjection.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/issueCommandAttachments.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsx": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts": {"resetModules": 2},@@ -815,21 +671,6 @@"apps/desktop/src/renderer/__tests__/menuButtonSettingsEntry.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/__tests__/messageDisclosureAnchorIntegration.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/messageRenderItemDom.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts": {- "sourceReads": 1- },- "apps/desktop/src/renderer/__tests__/messageViewportRestoreDom.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx": {"sourceReads": 3},@@ -883,9 +724,6 @@"sourceReads": 2},"apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx": {- "sourceReads": 5- },- "apps/desktop/src/renderer/__tests__/previousQuestionPlaceholder.test.tsx": {"sourceReads": 1},"apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts": {@@ -903,9 +741,6 @@"apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.ts": {"resetModules": 2},- "apps/desktop/src/renderer/__tests__/remoteBotLampFoldExemption.test.tsx": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/remoteCatalogSnapshot.test.ts": {"resetModules": 1},@@ -918,9 +753,6 @@"apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts": {"sourceReads": 12},- "apps/desktop/src/renderer/__tests__/restoredScrollIndicator.test.tsx": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts": {"sourceReads": 1},@@ -933,15 +765,9 @@"apps/desktop/src/renderer/__tests__/rolePillWorkerErrorIndicator.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/scheduleDefaultModel.test.ts": {"resetModules": 1},- "apps/desktop/src/renderer/__tests__/selectedFavoritePersistenceRollback.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/selectedMachineOwnerState.test.ts": {"resetModules": 1},@@ -966,9 +792,6 @@"apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts": {"sourceReads": 2},- "apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts": {"resetModules": 1},@@ -1056,9 +879,6 @@"apps/desktop/src/renderer/features/cc-agent/__tests__/newMakerDraftModelPrefs.test.ts": {"sourceReads": 1},- "apps/desktop/src/renderer/features/cc-agent/__tests__/newMakerDraftTargetCatalog.test.ts": {- "sourceReads": 1- },"apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupStore.test.ts": {"resetModules": 2},@@ -1188,9 +1008,6 @@"apps/mobile/src/__tests__/iosAppDistribution.test.ts": {"resetModules": 2},- "apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts": {- "sourceReads": 3- },"apps/mobile/src/__tests__/messageCacheStorage.test.ts": {"resetModules": 2},@@ -1207,8 +1024,7 @@"resetModules": 1},"apps/mobile/src/__tests__/outboxHistoryCache.test.ts": {- "realWaits": 1,- "sourceReads": 1+ "realWaits": 1},"apps/mobile/src/__tests__/remoteHistoryReentry.test.ts": {"sourceReads": 1@@ -1216,9 +1032,6 @@"apps/mobile/src/__tests__/remoteResourceCache.test.ts": {"resetModules": 2},- "apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts": {- "sourceReads": 1- },"apps/mobile/src/__tests__/useBotGroupChat.test.tsx": {"realWaits": 2},@@ -1228,9 +1041,6 @@"apps/mobile/src/__tests__/visualMock.test.ts": {"resetModules": 1},- "apps/mobile/src/auth/__tests__/loginFirstLaunchGate.test.ts": {- "resetModules": 1- },"apps/mobile/src/debug/localDiagnostics.test.ts": {"resetModules": 1},diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 6ad4d12e90..aa4671683d 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -96,6 +96,21 @@ const desktopE2eInclude = ['src/main/maker-host/__tests__/*.e2e.test.ts',];const mobileGuardInclude = [+ // Swift/delegate authorization, recording lifecycle, and native clipping are cross-runtime contracts.+ 'src/__tests__/mobileNativeBoundaryContracts.test.ts',+ 'src/__tests__/messageNativeLifecycleContracts.test.ts',+ 'src/__tests__/nativeE2eContracts.test.ts',+ // Credential ownership, retry protocol, and cross-file design contracts:+ // these read production sources to cover call-site boundaries, not runtime behavior.+ 'src/__tests__/authWeakNetworkBootstrap.test.ts',+ 'src/__tests__/mobileAuthServerLogin.test.ts',+ 'src/__tests__/messageSelectionHighlight.test.ts',+ 'src/__tests__/precreatedWorktreeRecoveryBridge.test.ts',+ 'src/__tests__/remoteListIncludePinned.test.ts',+ 'src/__tests__/revokedAccessTipDismissal.test.ts',+ 'src/__tests__/sendEnqueueRetry.test.ts',+ 'src/__tests__/sessionScreenshotShare.test.ts',+ 'src/auth/__tests__/xdOrgBetaWiring.test.ts',// CSP must be applied at the WebView and download call sites, not only in its helper.'src/__tests__/htmlPreviewCsp.test.ts','src/auth/__tests__/loginHandoffState.test.ts',@@ -131,6 +146,28 @@ const mobileGuardInclude = [// 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/renderer/__tests__/sessionAgentSwitchRemoteRouting.contract.test.ts',+ // Existing credential/permission/protocol contracts, separated from runtime units.+ 'src/main/__tests__/analyticsConsentMigrationGuards.test.ts',+ 'src/main/__tests__/authAccountDeletionLifecycle.test.ts',+ 'src/main/__tests__/authLegacyTokenMirror.test.ts',+ 'src/main/__tests__/authPassiveSharedInstance.test.ts',+ 'src/main/__tests__/authSessionExpiredDetection.test.ts',+ 'src/main/ghost-panel-window/__tests__/preload-contract.test.ts',+ 'src/main/right-sidebar-window/__tests__/preload-contract.test.ts',+ 'src/main/maker-ipc/__tests__/piPackageEnableConfirmationIpc.test.ts',+ 'src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts',+ 'src/renderer/__tests__/xUsageGuideRiskContrast.test.ts',+ 'src/main/__tests__/authHostedCallback.contract.test.ts',+ 'src/main/__tests__/loginScenarioHarness.contract.test.ts',+ 'src/main/__tests__/officialProfileMigrationPolicy.contract.test.ts',+ 'src/renderer/__tests__/authContextRace.contract.test.ts',+ 'src/main/__tests__/mobileClientPromptNote.contract.test.ts',+ 'src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.contract.test.ts',+ 'src/main/cindy-brain/__tests__/codexImageAuthBinding.contract.test.ts',+ 'src/main/__tests__/authCredentialStoreHealth.contract.test.ts',+ 'src/main/__tests__/authLoginFlowReset.contract.test.ts',+ 'src/main/maker-ipc/__tests__/messageDeleteHandler.contract.test.ts','src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts','src/renderer/__tests__/userMessageSourceLabels.test.ts',// These native host suites also protect cross-runtime privacy/permissiondiff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjsindex b6775bb1aa..9c61896024 100644--- a/scripts/test-workspaces.mjs+++ b/scripts/test-workspaces.mjs@@ -3,6 +3,7 @@ import { execFileSync, spawn } from "node:child_process";import fs from "node:fs";import os from "node:os";import path from "node:path";+import { createRequire } from "node:module";import { fileURLToPath } from "node:url";import {electronBinaryCheckSkipReason,@@ -16,6 +17,7 @@ import {import { createRelatedUnitPlan } from "./test-related.mjs";const ROOT = path.resolve(fileURLToPath(new URL("..", import.meta.url)));+const require = createRequire(import.meta.url);const IGNORED_PARTS = new Set(["node_modules","dist",@@ -557,6 +559,35 @@ export function buildPreflightArgs(root, workspace, preflight) {throw new Error(`Unsupported preflight type: ${preflight.type}`);}+export function resolveTestInvocation(pnpmArgs, options = {}) {+ const platform = options.platform ?? process.platform;+ if (platform !== "win32" || pnpmArgs[2] !== "exec" || pnpmArgs[3] !== "vitest") {+ return resolvePnpmInvocation(pnpmArgs, options);+ }+ // pnpm exec resolves vitest.cmd on Windows, which crosses cmd.exe's 8191+ // character limit once the required guard exclusions grow. Start the same+ // installed JS entry directly; preserve every selection/shard/exclusion arg.+ const execPath = options.execPath ?? process.execPath;+ const vitestEntry = options.vitestEntry ?? require.resolve("vitest/vitest.mjs");+ const env = { ...(options.env ?? process.env) };+ const pathKeys = Object.keys(env).filter((key) => key.toLowerCase() === "path");+ const pathKey = pathKeys[0] ?? "Path";+ const existingPath = env[pathKey] ?? "";+ for (const key of pathKeys) delete env[key];+ env[pathKey] = [+ path.dirname(execPath),+ path.join(pnpmArgs[1], "node_modules", ".bin"),+ path.join(ROOT, "node_modules", ".bin"),+ existingPath,+ ].join(";");+ return {+ command: execPath,+ args: [vitestEntry, ...pnpmArgs.slice(4)],+ shell: false,+ env,+ };+}+export function createOutputForwarder(stream) {let writable = Boolean(stream);let unexpectedError = null;@@ -923,7 +954,7 @@ export async function runPlannedTests({fileCheck.selected,Array.isArray(relatedFiles) ? relatedFiles : undefined,);- const invocation = resolvePnpmInvocation(pnpmArgs);+ const invocation = resolveTestInvocation(pnpmArgs);const commandResult = await runCommandImpl(invocation.command,invocation.args,