Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 新建任务按设备记住上次显式选择的项目目录,重进不再回退到最近首项 (#4113)
fico-hubdfbcfc6eafac
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex c51b4d58bf..8419a5cba6 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -453,6 +453,7 @@ export default function NewRemoteSessionScreen() {const [selectedDeviceId, setSelectedDeviceId] = useState(routeDeviceId);const [selectedDeviceName, setSelectedDeviceName] = useState(routeDeviceName);const [newSessionPreferences, setNewSessionPreferences] = useState<NewSessionStoredPreferences | null>(null);+ const workingDirPreferenceOverridesRef = useRef<Record<string, string>>({});const [newSessionPreferencesLoaded, setNewSessionPreferencesLoaded] = useState(false);const [devicePickerOpen, setDevicePickerOpen] = useState(false);const preferredDefaultDevice = useMemo(@@ -838,7 +839,11 @@ export default function NewRemoteSessionScreen() {void readNewSessionPreferences().then((preferences) => {if (cancelled) return;- setNewSessionPreferences(preferences);+ // A late initial read must not replace directories explicitly chosen while it was pending.+ setNewSessionPreferences({+ ...preferences,+ workingDirByDevice: { ...preferences.workingDirByDevice, ...workingDirPreferenceOverridesRef.current },+ });const workspaceKind = preferences.workspaceKind;if (!initialWorkingDir && workspaceKind) {setDraft((current) => userTouchedWorkspaceRef.current@@ -2148,6 +2153,26 @@ export default function NewRemoteSessionScreen() {setShowHiddenDirectories(false);}, [patchDraft]);+ // 用户显式选定目录 → 该设备的目录记忆(#4103):同步进本地 state(本页内切走再切回+ // 也拿最新值,落盘不回写 state,对齐 selectPermissionMode)并返回落盘 patch 片段。+ // 路径原样保存,只用 trim 判空(首尾空格可能是路径的一部分)。设备未定时不记。+ const rememberWorkingDirForDevice = useCallback((workingDir: string) => {+ if (!selectedDeviceId || !workingDir.trim()) return undefined;+ workingDirPreferenceOverridesRef.current[selectedDeviceId] = workingDir;+ setNewSessionPreferences((prev) => prev+ ? { ...prev, workingDirByDevice: { ...prev.workingDirByDevice, [selectedDeviceId]: workingDir } }+ : prev);+ return { deviceId: selectedDeviceId, workingDir };+ }, [selectedDeviceId]);++ // 用户显式选定目录(快捷选择 / 目录浏览器确认):按设备记住,下次空白新建先恢复它(#4103)。+ // 自动取最近项目首项走上面的 selectWorkingDir,不算显式选择,不写记忆。+ const chooseWorkingDir = useCallback((workingDir: string) => {+ const remembered = rememberWorkingDirForDevice(workingDir);+ if (remembered) void saveNewSessionPreferences({ workingDirForDevice: remembered });+ selectWorkingDir(workingDir);+ }, [rememberWorkingDirForDevice, selectWorkingDir]);+const selectDialogueWorkspace = useCallback(() => {userTouchedWorkspaceRef.current = true;void saveNewSessionPreferences({ workspaceKind: 'dialogue' });@@ -2159,12 +2184,17 @@ export default function NewRemoteSessionScreen() {const selectRecentProject = useCallback((workingDir: string) => {userTouchedWorkspaceRef.current = true;- void saveNewSessionPreferences({ workspaceKind: 'project' });+ // 显式点选最近项目 = 该设备的目录记忆(#4103);设备未定时只记模式。+ const remembered = rememberWorkingDirForDevice(workingDir);+ void saveNewSessionPreferences({+ workspaceKind: 'project',+ ...(remembered ? { workingDirForDevice: remembered } : {}),+ });patchDraft({ workspaceKind: 'project', workingDir });setWorkspacePickerOpen(false);setBrowseOpen(false);setShowHiddenDirectories(false);- }, [patchDraft]);+ }, [patchDraft, rememberWorkingDirForDevice]);const openProjectBrowse = useCallback(() => {userTouchedWorkspaceRef.current = true;@@ -3697,7 +3727,12 @@ export default function NewRemoteSessionScreen() {if (initialWorkspaceKeyRef.current === key) return;initialWorkspaceKeyRef.current = key;- const initialWorkspace = pickInitialNewSessionWorkspace(draft.workingDir, recentWorkspaces);+ // 先用该设备记住的上次显式选择(#4103),没有再取最近项目首项。+ const initialWorkspace = pickInitialNewSessionWorkspace(+ draft.workingDir,+ recentWorkspaces,+ newSessionPreferences?.workingDirByDevice?.[selectedDeviceId] ?? null,+ );if (initialWorkspace) {selectWorkingDir(initialWorkspace);return;@@ -3714,6 +3749,7 @@ export default function NewRemoteSessionScreen() {recentWorkspaces,selectWorkingDir,newSessionPreferencesLoaded,+ newSessionPreferences?.workingDirByDevice,preferredDefaultDevice?.deviceId,]);@@ -5640,7 +5676,7 @@ export default function NewRemoteSessionScreen() {accessibilityRole="button"disabled={creating}key={workspace.workingDir}- onPress={() => selectWorkingDir(workspace.workingDir)}+ onPress={() => chooseWorkingDir(workspace.workingDir)}style={({ pressed }) => [styles.workspaceQuickPick, pressed && styles.pressed]}testID="newSession.workspaceQuickPick">@@ -5668,7 +5704,7 @@ export default function NewRemoteSessionScreen() {accessibilityLabel={t('session.new.useCurrentRemoteDir')}accessibilityRole="button"disabled={!browsePath || browseLoading}- onPress={() => browsePath && selectWorkingDir(browsePath)}+ onPress={() => browsePath && chooseWorkingDir(browsePath)}style={({ pressed }) => [styles.browseActionButton,(!browsePath || browseLoading) && styles.disabled,@@ -5715,7 +5751,7 @@ export default function NewRemoteSessionScreen() {disabled={creating || browseLoading}entry={item}onEnter={() => void loadBrowsePath(item.path)}- onSelect={() => selectWorkingDir(item.path)}+ onSelect={() => chooseWorkingDir(item.path)}/>)}nestedScrollEnableddiff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.tsindex d2c3206bb3..0c4e3b3ea0 100644--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts@@ -36,7 +36,7 @@ describe('auth weak-network bootstrap', () => {'activateMobileSessionRealm(storedSession.realm);',);const publishUserAt = restoreBody.indexOf('setUser(cachedUser);');- const publishOwnerAt = restoreBody.indexOf('setMobileAuthOwner(cachedUser.id);');+ const publishOwnerAt = restoreBody.indexOf('setMobileAuthOwner(cachedUser.id, storedSession.realm);');expect(loadRealmAt).toBeGreaterThanOrEqual(0);expect(activateRealmAt).toBeGreaterThan(loadRealmAt);expect(publishOwnerAt).toBeGreaterThan(activateRealmAt);@@ -63,7 +63,7 @@ describe('auth weak-network bootstrap', () => {const applyUserStart = authSource.indexOf('const applyUser = useCallback');const applyUserEnd = authSource.indexOf('\n );', applyUserStart);const applyUserBody = authSource.slice(applyUserStart, applyUserEnd);- expect(applyUserBody.indexOf('setMobileAuthOwner(next?.id);'))+ expect(applyUserBody.indexOf('setMobileAuthOwner(next?.id, activeAuthRealmRef.current);')).toBeLessThan(applyUserBody.indexOf('setUser(next);'));expect(applyUserBody).toContain('accountVaultKey(activeAuthRealmRef.current, next.id)',diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex d3fd5eed33..68b5fddfd7 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1441,6 +1441,22 @@ describe('new session model', () => {expect(pickInitialNewSessionWorkspace('', [])).toBeNull();});+ it('prefers the directory the user last explicitly chose on this device over the most recent workspace (#4103)', () => {+ const recentWorkspaces = buildRecentWorkspaceOptions([+ remoteSession('latest', { workingDir: '/repo/latest', userSendAt: '2026-01-01T00:10:00.000Z' }),+ remoteSession('third', { workingDir: '/repo/third', userSendAt: '2026-01-01T00:01:00.000Z' }),+ ]);+ // 记忆的目录优先;不要求它仍在最近列表里(列表只保留 6 项,用户本就可从浏览器选任意目录)+ expect(pickInitialNewSessionWorkspace('', recentWorkspaces, '/repo/third')).toBe('/repo/third');+ // 路径原样返回:首尾空格可能是目录名的一部分(review:Greptile P1)+ expect(pickInitialNewSessionWorkspace('', recentWorkspaces, ' /elsewhere/app ')).toBe(' /elsewhere/app ');+ expect(pickInitialNewSessionWorkspace('', [], '/repo/third')).toBe('/repo/third');+ // 草稿已有目录时仍然不动;没有记忆时回落最近项目首项+ expect(pickInitialNewSessionWorkspace('/explicit', recentWorkspaces, '/repo/third')).toBeNull();+ expect(pickInitialNewSessionWorkspace('', recentWorkspaces, null)).toBe('/repo/latest');+ expect(pickInitialNewSessionWorkspace('', recentWorkspaces, ' ')).toBe('/repo/latest');+ });+it('normalizes create results and can synthesize a fallback session row', () => {const result = normalizeCreateSessionResult({sessionId: 's-new',diff --git a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.tsindex f393b7cd64..67a4b60a9d 100644--- a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts+++ b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts@@ -1,3 +1,7 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { accountVaultKey } from '@cindy/auth-client';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { beforeEach, describe, expect, it, vi } from 'vitest';const store = vi.hoisted(() => new Map<string, string>());@@ -21,6 +25,82 @@ describe('newSessionPreferenceStore', () => {const { clearNewSessionPreferences } = await import('@/session/newSessionPreferenceStore');await clearNewSessionPreferences();store.clear();+ setMobileAuthOwner('account-a');+ });++ it('isolates directories on the same device across accounts and signed-out reads', async () => {+ const { readNewSessionPreferences, saveNewSessionPreferences } =+ await import('@/session/newSessionPreferenceStore');+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/account-a/private' } });+ setMobileAuthOwner('account-b');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({});+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/account-b/private' } });+ setMobileAuthOwner(null);+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({});+ setMobileAuthOwner('account-a');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({ 'shared-device': '/account-a/private' });+ setMobileAuthOwner('account-b');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({ 'shared-device': '/account-b/private' });+ });++ it('does not adopt the unowned legacy directory map into a logged-in account', async () => {+ const { __testing, readNewSessionPreferences } = await import('@/session/newSessionPreferenceStore');+ store.set(__testing.storageKey, JSON.stringify({ agentKind: 'codex', workingDirByDevice: { devA: '/previous-owner/private' } }));+ expect(await readNewSessionPreferences()).toMatchObject({ agentKind: 'codex', workingDirByDevice: {} });+ });++ it('does not attribute a queued directory save or late read to the next account', async () => {+ const { readNewSessionPreferences, saveNewSessionPreferences } =+ await import('@/session/newSessionPreferenceStore');+ const saving = saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/account-a/private' } });+ const reading = readNewSessionPreferences();+ setMobileAuthOwner('account-b');+ await saving;+ expect((await reading).workingDirByDevice).toEqual({});+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({});+ });++ it('isolates equal membership IDs across realms and invalidates pending work', async () => {+ const { __testing, readNewSessionPreferences, saveNewSessionPreferences } =+ await import('@/session/newSessionPreferenceStore');+ store.set(__testing.workingDirStorageKey('shared-member'), JSON.stringify({+ 'shared-device': '/unqualified/private',+ }));+ setMobileAuthOwner('shared-member', 'cn');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({});+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/cn/private' } });+ const cnOwner = getMobileAuthOwner();+ const saving = saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/cn/pending' } });+ const reading = readNewSessionPreferences();+ setMobileAuthOwner('shared-member', 'global');+ expect(isMobileAuthOwnerCurrent(cnOwner)).toBe(false);+ await saving;+ expect((await reading).workingDirByDevice).toEqual({});+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({});+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'shared-device', workingDir: '/global/private' } });+ setMobileAuthOwner('shared-member', 'cn');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({ 'shared-device': '/cn/private' });+ setMobileAuthOwner('shared-member', 'global');+ expect((await readNewSessionPreferences()).workingDirByDevice).toEqual({ 'shared-device': '/global/private' });+ });++ it('keeps the bare owner ID accepted by both live creation guards and recovery namespaces', () => {+ setMobileAuthOwner('shared-member', 'cn');+ // 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);+ for (const [, predicate] of guards) {+ const accepts = new Function('authOwnerAtCreate', 'accountIdAtCreate', 'isMobileAuthOwnerCurrent', `return (${predicate});`);+ const currentOwner = getMobileAuthOwner();+ expect(accepts(currentOwner, 'shared-member', isMobileAuthOwnerCurrent)).toBe(true);+ setMobileAuthOwner('shared-member', 'global');+ expect(accepts(currentOwner, 'shared-member', isMobileAuthOwnerCurrent)).toBe(false);+ setMobileAuthOwner('shared-member', 'cn');+ }+ // 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);});it('stores the last selected device and agent for new sessions', async () => {@@ -40,6 +120,7 @@ describe('newSessionPreferenceStore', () => {device: { deviceId: 'devA', name: 'Mac A' },workspaceKind: null,permissionModeByAgent: {},+ workingDirByDevice: {},});expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({agentKind: 'codex',@@ -66,6 +147,7 @@ describe('newSessionPreferenceStore', () => {device: { deviceId: 'devB', name: 'devB' },workspaceKind: null,permissionModeByAgent: {},+ workingDirByDevice: {},});store.set(__testing.storageKey, '{broken');@@ -74,6 +156,7 @@ describe('newSessionPreferenceStore', () => {device: null,workspaceKind: null,permissionModeByAgent: {},+ workingDirByDevice: {},});await saveNewSessionPreferences({@@ -84,6 +167,7 @@ describe('newSessionPreferenceStore', () => {device: { deviceId: 'devC', name: 'devC' },workspaceKind: null,permissionModeByAgent: {},+ workingDirByDevice: {},});});@@ -110,6 +194,7 @@ describe('newSessionPreferenceStore', () => {device: null,workspaceKind: null,permissionModeByAgent: { 'claude-code': 'bypassPermissions', codex: 'ask' },+ workingDirByDevice: {},});// 落盘的 plan / 非法 agent 键在读取时被清洗。@@ -121,7 +206,45 @@ describe('newSessionPreferenceStore', () => {device: null,workspaceKind: null,permissionModeByAgent: { codex: 'auto' },+ workingDirByDevice: {},+ });+ });++ it('remembers the last explicitly chosen project directory per device (#4103)', async () => {+ const {+ __testing,+ readNewSessionPreferences,+ saveNewSessionPreferences,+ } = await import('@/session/newSessionPreferenceStore');++ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'devA', workingDir: '/repo/third' } });+ // 路径原样保存:首尾空格可能是目录名的一部分(review:Greptile P1)+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'devB', workingDir: ' /other/app ' } });+ // 同设备再次选择覆盖上次;空值 / 空设备被忽略,不清掉已有记忆。+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'devA', workingDir: '/repo/fourth' } });+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: 'devA', workingDir: ' ' } });+ await saveNewSessionPreferences({ workingDirForDevice: { deviceId: '', workingDir: '/nope' } });+ await saveNewSessionPreferences({ workspaceKind: 'dialogue' });++ await expect(readNewSessionPreferences()).resolves.toEqual({+ agentKind: null,+ device: null,+ workspaceKind: 'dialogue',+ permissionModeByAgent: {},+ workingDirByDevice: { devA: '/repo/fourth', devB: ' /other/app ' },+ });+ expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({+ workspaceKind: 'dialogue',+ });+ expect(JSON.parse(store.get(__testing.workingDirStorageKey(accountVaultKey('global', 'account-a'))) ?? '{}')).toEqual({ devA: '/repo/fourth', devB: ' /other/app ' });++ // 落盘里的非法条目(非字符串 / 空)在读取时被清洗,旧存储没有该字段也不报错。+ store.set(__testing.workingDirStorageKey(accountVaultKey('global', 'account-a')), JSON.stringify({ devA: '/repo/ok', devB: 42, ' ': '/x', devC: '', devD: ' /keep me ' }));+ await expect(readNewSessionPreferences()).resolves.toMatchObject({+ workingDirByDevice: { devA: '/repo/ok', devD: ' /keep me ' },});+ store.set(__testing.workingDirStorageKey(accountVaultKey('global', 'account-a')), JSON.stringify('bad'));+ await expect(readNewSessionPreferences()).resolves.toMatchObject({ workingDirByDevice: {} });});it('remembers either workspace mode across reloads without losing other preferences', async () => {@@ -148,6 +271,7 @@ describe('newSessionPreferenceStore', () => {workspaceKind: 'dialogue',agentKind: 'codex',permissionModeByAgent: { codex: 'ask' },+ workingDirByDevice: {},});});diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsxindex 152e9a7dac..d47d0e51e9 100644--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx@@ -25,9 +25,11 @@ const page = source.statements.find((node): node is ts.FunctionDeclaration =>if (!page?.body) throw new Error('NewRemoteSessionScreen not found');const declarations = new Set(['selectedDeviceId', 'selectedDeviceName', 'newSessionPreferences', 'newSessionPreferencesLoaded',+ 'workingDirPreferenceOverridesRef','preferredDefaultDevice', 'recentWorkspaces', 'draft', 'initialWorkspaceKeyRef','appliedDefaultDeviceKeyRef', 'userTouchedDeviceRef', 'userTouchedWorkspaceRef',- 'patchDraft', 'selectWorkingDir', 'selectDialogueWorkspace', 'selectRecentProject', 'openProjectBrowse',+ 'patchDraft', 'selectWorkingDir', 'rememberWorkingDirForDevice', 'selectDialogueWorkspace',+ 'selectRecentProject', 'openProjectBrowse',]);const effectMarkers = new Set(['drainStashedNewSessionDraft', 'readNewSessionPreferences',@@ -67,6 +69,8 @@ interface WorkspaceState {selectDialogueWorkspace(): void;selectRecentProject(path: string): void;openProjectBrowse(): void;+ /** 模拟页面 selectDevice 里与工作区相关的部分:标记用户动过设备、重置初始工作区决策、清空项目目录。 */+ switchDevice(deviceId: string): void;}const bindingNames = ['useState', 'useRef', 'useMemo', 'useEffect', 'useCallback', 'DEFAULT_NEW_SESSION_DRAFT',@@ -80,8 +84,14 @@ const bindingNames = [const compiled = ts.transpileModule(`function usePageWorkspace(bindings) {const { ${bindingNames.join(', ')} } = bindings;${selected.map((statement) => statement.getText(source)).join('\n')}+ const switchDevice = (deviceId) => {+ userTouchedDeviceRef.current = true;+ initialWorkspaceKeyRef.current = null;+ setSelectedDeviceId(deviceId);+ setDraft((current) => current.workspaceKind === 'project' ? { ...current, workingDir: '' } : current);+ };return { draft, selectedDeviceId, newSessionPreferencesLoaded,- selectDialogueWorkspace, selectRecentProject, openProjectBrowse };+ selectDialogueWorkspace, selectRecentProject, openProjectBrowse, switchDevice };}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;const usePageWorkspace = new Function(`${compiled}; return usePageWorkspace;`)() as(bindings: Record<string, unknown>) => WorkspaceState;@@ -130,10 +140,14 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Neact(() => root!.render(createElement(Harness)));return {bindings, commits, get current() { return current; },- async resolvePreferences(kind: NewSessionWorkspaceKind | null, deviceId = 'a') {+ async resolvePreferences(+ kind: NewSessionWorkspaceKind | null,+ deviceId = 'a',+ workingDirByDevice: Record<string, string> = {},+ ) {await act(async () => {resolveRead({ workspaceKind: kind, device: { deviceId, name: deviceId },- agentKind: null, permissionModeByAgent: {} });+ agentKind: null, permissionModeByAgent: {}, workingDirByDevice });await pendingRead;});},@@ -141,6 +155,19 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Ne}describe('new session workspace page effects', () => {+ it('keeps choices for both devices made before the stored preferences arrive', async () => {+ const page = mountWorkspace();+ act(() => page.current.selectRecentProject(' /manual/a '));+ act(() => page.current.switchDevice('b'));+ act(() => page.current.selectRecentProject('/manual/b'));+ await page.resolvePreferences('project', 'a', { a: '/old/a', b: '/old/b' });+ act(() => page.current.switchDevice('a'));+ expect(page.current.draft.workingDir).toBe(' /manual/a ');+ act(() => page.current.switchDevice('b'));+ expect(page.current.draft.workingDir).toBe('/manual/b');+ expect(page.bindings.saveNewSessionPreferences).toHaveBeenCalledTimes(2);+ });+it('keeps an explicit project entry when a different preference arrives late', async () => {const page = mountWorkspace({ initialWorkingDir: '/explicit/project' });await page.resolvePreferences('dialogue', 'b');@@ -166,7 +193,10 @@ describe('new session workspace page effects', () => {await page.resolvePreferences(kind === 'project' ? 'dialogue' : 'project');expect(page.current.draft).toMatchObject({ workspaceKind: kind,workingDir: kind === 'project' ? '/manual/project' : '' });- expect(page.bindings.saveNewSessionPreferences).toHaveBeenCalledWith({ workspaceKind: kind });+ expect(page.bindings.saveNewSessionPreferences).toHaveBeenCalledWith(kind === 'project'+ // 显式点选最近项目同时按设备记住目录(#4103)+ ? { workspaceKind: 'project', workingDirForDevice: { deviceId: 'a', workingDir: '/manual/project' } }+ : { workspaceKind: 'dialogue' });});it('keeps an explicitly opened project browser open after a late dialogue preference', async () => {@@ -192,6 +222,40 @@ describe('new session workspace page effects', () => {expect(page.bindings.loadBrowsePath).not.toHaveBeenCalled();});+ it('restores the directory last explicitly chosen on the remembered device instead of the most recent one (#4103)', async () => {+ const page = mountWorkspace();+ // 用户上次在设备 b 显式选了第三个目录(它甚至不在最近列表里);重进后应恢复它而不是最近首项 /projects/b+ await page.resolvePreferences('project', 'b', { b: '/projects/third', a: '/projects/other' });+ expect(page.current.selectedDeviceId).toBe('b');+ expect(page.current.draft).toMatchObject({ workspaceKind: 'project', workingDir: '/projects/third' });+ expect(page.bindings.pickInitialNewSessionWorkspace).toHaveBeenCalledTimes(1);+ // 自动恢复不算显式选择:不得把它再写回目录记忆+ expect(page.bindings.saveNewSessionPreferences).not.toHaveBeenCalledWith(+ expect.objectContaining({ workingDirForDevice: expect.anything() }),+ );+ expect(page.bindings.loadBrowsePath).not.toHaveBeenCalled();+ });++ it('uses the directory chosen in this session after switching devices and back, not the stale stored one (#4103 Codex P2)', async () => {+ const page = mountWorkspace();+ await page.resolvePreferences('project', 'a', { a: '/projects/old-a' });+ expect(page.current.draft.workingDir).toBe('/projects/old-a');+ // 本页内显式换成新目录 → 内存里的设备记忆同步更新(落盘不回写 state)+ act(() => page.current.selectRecentProject('/projects/new-a'));+ expect(page.current.draft.workingDir).toBe('/projects/new-a');+ // 切到 b(无记忆 → 最近首项),再切回 a:应恢复本页刚选的 new-a,而不是读取时的 old-a+ act(() => page.current.switchDevice('b'));+ expect(page.current.draft.workingDir).toBe('/projects/b');+ act(() => page.current.switchDevice('a'));+ expect(page.current.draft.workingDir).toBe('/projects/new-a');+ });++ it('falls back to the most recent workspace when only another device has a remembered directory', async () => {+ const page = mountWorkspace();+ await page.resolvePreferences('project', 'b', { a: '/projects/other' });+ expect(page.current.draft).toMatchObject({ workspaceKind: 'project', workingDir: '/projects/b' });+ });+it('keeps the existing default when storage has no remembered mode', async () => {const page = mountWorkspace();await page.resolvePreferences(null);diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex e6e9d95102..4e597b9c26 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -817,7 +817,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {? accountVaultKey(activeAuthRealmRef.current, next.id): null;setDeferredSessionRecovery(false);- setMobileAuthOwner(next?.id);+ setMobileAuthOwner(next?.id, activeAuthRealmRef.current);userRef.current = next;setUser(next);void serializeUserProfileMutation(() =>@@ -1072,7 +1072,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// old owner and advance its generation after cleanup settles so// account-scoped effects reconnect from the restored session.activateMobileSessionRealm(previousRealm);- setMobileAuthOwner(userRef.current?.id ?? null);+ setMobileAuthOwner(userRef.current?.id ?? null, previousRealm);setAccountGeneration((value) => value + 1);}throw error;@@ -1436,7 +1436,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {activateMobileSessionRealm(storedSession.realm);activeAuthRealmRef.current = storedSession.realm;userRef.current = cachedUser;- setMobileAuthOwner(cachedUser.id);+ setMobileAuthOwner(cachedUser.id, storedSession.realm);setUser(cachedUser);if (cachedProfile.accountKey === null) {void serializeUserProfileMutation(() =>@@ -2472,14 +2472,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {authGenerationRef.current === generation) {activateMobileSessionRealm(previousRealm);- setMobileAuthOwner(userRef.current?.id ?? null);+ setMobileAuthOwner(userRef.current?.id ?? null, previousRealm);setAccountGeneration((value) => value + 1);}throw error;}});} catch (error) {- setMobileAuthOwner(userRef.current?.id ?? null);+ setMobileAuthOwner(userRef.current?.id ?? null, activeAuthRealmRef.current);throw error;}@@ -2535,7 +2535,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {sessionRecoverySuspendedRef.current = false;await deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined);activateMobileSessionRealm(activeAuthRealmRef.current);- setMobileAuthOwner(userRef.current?.id ?? null);+ setMobileAuthOwner(userRef.current?.id ?? null, activeAuthRealmRef.current);updateLoginState(null);setAuthError(null);}, [updateLoginState]);diff --git a/apps/mobile/src/auth/authOwnerGeneration.ts b/apps/mobile/src/auth/authOwnerGeneration.tsindex af1bf20ceb..153e1d7411 100644--- a/apps/mobile/src/auth/authOwnerGeneration.ts+++ b/apps/mobile/src/auth/authOwnerGeneration.ts@@ -1,19 +1,30 @@+import { accountVaultKey, type AuthRegion } from '@cindy/auth-client';+export interface MobileAuthOwnerGeneration {+ /** Bare membership ID retained for creation guards and recovery ledgers. */readonly accountId: string;+ /** Canonical realm-qualified key for new account-scoped storage. */+ readonly accountKey: string;readonly generation: number;}let current: MobileAuthOwnerGeneration = {accountId: '',+ accountKey: '',generation: 0,};/** Publish the account owner synchronously, before React state updates settle. */-export function setMobileAuthOwner(accountId: string | null | undefined): void {+export function setMobileAuthOwner(+ accountId: string | null | undefined,+ realm: AuthRegion = 'global',+): void {const normalized = accountId?.trim() ?? '';- if (current.accountId === normalized) return;+ const accountKey = normalized ? accountVaultKey(realm, normalized) : '';+ if (current.accountKey === accountKey) return;current = {accountId: normalized,+ accountKey,generation: current.generation + 1,};}@@ -26,13 +37,13 @@ export function isMobileAuthOwnerCurrent(owner: MobileAuthOwnerGeneration,): boolean {return (- current.accountId === owner.accountId+ current.accountKey === owner.accountKey&& current.generation === owner.generation);}export const __testing = {reset(): void {- current = { accountId: '', generation: 0 };+ current = { accountId: '', accountKey: '', generation: 0 };},};diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex ef0ab88fe4..c0612a3454 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -83,6 +83,12 @@ export interface NewSessionStoredPreferences {* 没选过 = 缺失,回落该 agent 的安全种子默认。'plan' 不入记忆(计划模式是独立开关)。*/permissionModeByAgent: Partial<Record<NewSessionAgentKind, string>>;+ /**+ * 每台被控电脑上次在新建页**显式选择**的项目目录(deviceId → 绝对路径,#4103)。+ * 只在用户点选最近项目 / 在目录浏览器里确认时写入;自动取最近项目首项不算显式选择。+ * 按设备归属,避免把一台电脑的路径套到另一台;没有记忆的设备沿用最近项目默认逻辑。+ */+ workingDirByDevice: Record<string, string>;}export interface NewSessionDraftSummary {@@ -824,11 +830,19 @@ export function resolveNewSessionAutoDefault(input: {};}+/**+ * 空白新建的初始项目目录:草稿已有目录 → 不动;否则先用该设备记住的上次显式选择+ * (#4103,不要求它仍在最近列表里——列表只保留 6 项,且用户本就有目录浏览入口),+ * 没有记忆再取最近项目首项。+ */export function pickInitialNewSessionWorkspace(currentWorkingDir: string,recentWorkspaces: readonly RecentWorkspaceOption[],+ rememberedWorkingDir?: string | null,): string | null {if (currentWorkingDir.trim()) return null;+ // 记忆目录原样返回(首尾空格可能是路径的一部分),只用 trim 判空。+ if (rememberedWorkingDir?.trim()) return rememberedWorkingDir;return recentWorkspaces[0]?.workingDir ?? null;}diff --git a/apps/mobile/src/session/newSessionPreferenceStore.ts b/apps/mobile/src/session/newSessionPreferenceStore.tsindex edd79dd739..17ccc470aa 100644--- a/apps/mobile/src/session/newSessionPreferenceStore.ts+++ b/apps/mobile/src/session/newSessionPreferenceStore.ts@@ -1,3 +1,8 @@+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+ type MobileAuthOwnerGeneration,+} from '@/auth/authOwnerGeneration';import AsyncStorage from '@react-native-async-storage/async-storage';import {normalizeNewSessionAgentKind,@@ -15,36 +20,62 @@ export interface NewSessionPreferencePatch {workspaceKind?: NewSessionWorkspaceKind;/** 记住某 agent 在新建页选的权限档(单键合并进 permissionModeByAgent;'plan' 被忽略)。 */permissionModeForAgent?: { agentKind: NewSessionAgentKind; mode: string };+ /** 记住某台被控电脑上次显式选择的项目目录(单键合并进 workingDirByDevice;空值被忽略,#4103)。 */+ workingDirForDevice?: { deviceId: string; workingDir: string };}export async function readNewSessionPreferences(): Promise<NewSessionStoredPreferences> {// 刚选完就重新打开新建页时,也要看到已提交但尚未落盘的选择。+ const owner = getMobileAuthOwner();await writeChain;- return loadNewSessionPreferences();+ const preferences = await loadNewSessionPreferences(owner.accountKey);+ return isMobileAuthOwnerCurrent(owner) ? preferences : { ...preferences, workingDirByDevice: {} };+}++function workingDirStorageKey(accountId: string): string {+ return `${STORAGE_KEY}.working-directories.${encodeURIComponent(accountId)}`;}-async function loadNewSessionPreferences(): Promise<NewSessionStoredPreferences> {- const raw = await AsyncStorage.getItem(STORAGE_KEY).catch(() => null);- if (!raw) return emptyPreferences();+async function loadNewSessionPreferences(accountId: string): Promise<NewSessionStoredPreferences> {+ const [raw, directories] = await Promise.all([+ AsyncStorage.getItem(STORAGE_KEY).catch(() => null),+ accountId ? AsyncStorage.getItem(workingDirStorageKey(accountId)).catch(() => null) : null,+ ]);+ let preferences = emptyPreferences();try {- return normalizeStoredPreferences(JSON.parse(raw));+ if (raw) preferences = normalizeStoredPreferences(JSON.parse(raw));} catch {- return emptyPreferences();+ // Malformed preferences fall back to defaults.}+ // The old global map has no provable owner; never assign it to the next account.+ try {+ if (directories) preferences.workingDirByDevice = normalizeWorkingDirByDevice(JSON.parse(directories));+ } catch {+ // A malformed directory map must not prevent loading the other preferences.+ }+ return preferences;}// 与首页偏好存储一致:连续选择不同字段时,读改写必须按操作顺序执行。let writeChain: Promise<void> = Promise.resolve();export function saveNewSessionPreferences(patch: NewSessionPreferencePatch): Promise<void> {- const next = writeChain.then(() => writeNewSessionPreferences(patch));+ const owner = getMobileAuthOwner();+ const next = writeChain.then(() => writeNewSessionPreferences(patch, owner));writeChain = next.catch(() => undefined);return next;}-async function writeNewSessionPreferences(patch: NewSessionPreferencePatch): Promise<void> {- const current = await loadNewSessionPreferences();+async function writeNewSessionPreferences(+ patch: NewSessionPreferencePatch,+ owner: MobileAuthOwnerGeneration,+): Promise<void> {+ const current = await loadNewSessionPreferences(owner.accountKey);const permissionPatch = patch.permissionModeForAgent;+ const workingDirPatch = patch.workingDirForDevice;+ const workingDirDeviceId = workingDirPatch?.deviceId.trim() ?? '';+ // 路径原样保存(macOS / Linux 允许目录名首尾带空格,浏览器也原样返回);只用 trim 判空。+ const workingDirValue = workingDirPatch && workingDirPatch.workingDir.trim() ? workingDirPatch.workingDir : '';const next: NewSessionStoredPreferences = {agentKind: patch.agentKind ?? current.agentKind,workspaceKind: patch.workspaceKind ?? current.workspaceKind,@@ -55,12 +86,23 @@ async function writeNewSessionPreferences(patch: NewSessionPreferencePatch): PropermissionPatch && isRememberablePermissionMode(permissionPatch.mode)? { ...current.permissionModeByAgent, [permissionPatch.agentKind]: permissionPatch.mode }: current.permissionModeByAgent,+ workingDirByDevice:+ workingDirDeviceId && workingDirValue+ ? { ...current.workingDirByDevice, [workingDirDeviceId]: workingDirValue }+ : current.workingDirByDevice,};await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(serializePreferences(next))).catch(() => undefined);+ if (workingDirDeviceId && workingDirValue && owner.accountKey && isMobileAuthOwnerCurrent(owner)) {+ await AsyncStorage.setItem(workingDirStorageKey(owner.accountKey), JSON.stringify(next.workingDirByDevice)).catch(() => undefined);+ }}export function clearNewSessionPreferences(): Promise<void> {- const next = writeChain.then(() => AsyncStorage.removeItem(STORAGE_KEY));+ const owner = getMobileAuthOwner();+ const next = writeChain.then(async () => {+ await AsyncStorage.removeItem(STORAGE_KEY);+ if (owner.accountKey) await AsyncStorage.removeItem(workingDirStorageKey(owner.accountKey));+ });writeChain = next.catch(() => undefined);return writeChain;}@@ -71,9 +113,22 @@ function emptyPreferences(): NewSessionStoredPreferences {workspaceKind: null,device: null,permissionModeByAgent: {},+ workingDirByDevice: {},};}+function normalizeWorkingDirByDevice(value: unknown): Record<string, string> {+ const record = readRecord(value);+ if (!record) return {};+ const out: Record<string, string> = {};+ for (const [deviceId, workingDir] of Object.entries(record)) {+ const id = deviceId.trim();+ // 目录原样保留(首尾空格可能是路径的一部分),只剔除非字符串 / 纯空白。+ if (id && typeof workingDir === 'string' && workingDir.trim()) out[id] = workingDir;+ }+ return out;+}+// 'plan' 是计划模式的实现细节(老被控端兼容路径),不是用户可记忆的权限档。function isRememberablePermissionMode(mode: string): boolean {return mode.trim().length > 0 && mode !== 'plan';@@ -106,6 +161,7 @@ function normalizeStoredPreferences(value: unknown): NewSessionStoredPreferences? { deviceId, name: deviceName || deviceId }: null,permissionModeByAgent: normalizePermissionModeByAgent(record.permissionModeByAgent),+ workingDirByDevice: {},};}@@ -151,4 +207,5 @@ function readString(value: unknown): string | null {export const __testing = {storageKey: STORAGE_KEY,+ workingDirStorageKey,};diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 12148e04aa..3f38a39988 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -1168,6 +1168,7 @@ describe('DeviceLinkClient', () => {});it('入站 link 的可靠重试耗尽只重置该 peer link:relay 连接不拆,发 transport-timeout link-close,重开后 live 帧按原 seq 重放', async () => {+ vi.useFakeTimers();const warn = vi.fn();const h = makeHarness({timing: {@@ -1179,72 +1180,77 @@ describe('DeviceLinkClient', () => {},logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },});- h.client.start();- await tick();- h.current().ack();- await establishInboundReliableLink(h, 'inbound-timeout-stream');-- const firstSocket = h.current();- // 可丢弃前缀(陈旧实时镜像) + 不可丢弃的 live invoke-result- h.client.sendPush('dev-b', 'maker:event', { drop: 'me' });- h.client.sendInvokeResult('dev-b', 'keep-me', { ok: true, result: [] });- const firstReliable = firstSocket.sent.find((env) => (- env.kind === 'invoke-result' && parseTransportPayload(env.payload)- ))!;- const firstMeta = parseTransportPayload(firstReliable.payload)!.meta;-- // 对端永不 ACK → 重试耗尽 → 只重置该 peer 的 link 并通知对端- await vi.waitFor(() => {+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(0);+ h.current().ack();+ const initialOpen = establishInboundReliableLink(h, 'inbound-timeout-stream');+ await vi.advanceTimersByTimeAsync(0);+ await initialOpen;++ const firstSocket = h.current();+ // 可丢弃前缀(陈旧实时镜像) + 不可丢弃的 live invoke-result+ h.client.sendPush('dev-b', 'maker:event', { drop: 'me' });+ h.client.sendInvokeResult('dev-b', 'keep-me', { ok: true, result: [] });+ const firstReliable = firstSocket.sent.find((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ ))!;+ const firstMeta = parseTransportPayload(firstReliable.payload)!.meta;++ // 对端永不 ACK → 重试耗尽 → 只重置该 peer 的 link 并通知对端+ await vi.advanceTimersByTimeAsync(50);expect(firstSocket.sent.some((env) => (env.kind === 'link-close'&& env.dst === 'dev-b'&& (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'))).toBe(true);- });- // relay 连接毫发无损:既没 terminate,也没新建 socket(其它 peer 零感知)- expect(firstSocket.terminated).toBe(false);- expect(firstSocket.closed).toBeNull();- expect(h.sockets).toHaveLength(1);- expect(warn).toHaveBeenCalledWith(expect.stringMatching(- /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,- ));+ // relay 连接毫发无损:既没 terminate,也没新建 socket(其它 peer 零感知)+ expect(firstSocket.terminated).toBe(false);+ expect(firstSocket.closed).toBeNull();+ expect(h.sockets).toHaveLength(1);+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(+ /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,+ ));- // 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放- const sentBefore = firstSocket.sent.length;- await establishInboundReliableLink(h, 'inbound-timeout-stream');- // 模拟真实接收端:重放帧已写入 socket FIFO 后立即回 ACK(见 client.ts- // sendTransportAck 的交付即确认语义)。不 ACK 的话,重放后 retryTimer- // 会在 Windows 低精度计时器(≈12ms>配置 5ms)下把同一帧再发一遍,慢 CI- // runner 上断言窗口跨过该周期时会把「重试重发」误判成「重放两次」。- const justReplayed = firstSocket.sent.slice(sentBefore).filter((env) => (- env.kind === 'invoke-result' && parseTransportPayload(env.payload)- ));- if (justReplayed.length > 0) {- const meta = parseTransportPayload(justReplayed[0].payload)!.meta;- h.current().push({- v: PROTOCOL_VERSION,- kind: 'push',- src: 'dev-b',- payload: {- channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,- payload: { streamId: meta.streamId, ackSeq: meta.seq },- },+ // 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放+ const sentBefore = firstSocket.sent.length;+ const reopened = establishInboundReliableLink(h, 'inbound-timeout-stream');+ await vi.advanceTimersByTimeAsync(0);+ await reopened;+ // 受控时钟保持在重开时刻:真实计时器可能在 tick 等待期间已跨过 5ms+ // 重试窗口,此时再 ACK 也来不及阻止第二帧。确认重放后再 ACK,不放宽数量断言。+ const justReplayed = firstSocket.sent.slice(sentBefore).filter((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ ));+ if (justReplayed.length > 0) {+ const meta = parseTransportPayload(justReplayed[0].payload)!.meta;+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: meta.streamId, ackSeq: meta.seq },+ },+ });+ }+ const replayed = firstSocket.sent.slice(sentBefore);+ const replays = replayed.filter((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ ));+ expect(replays).toHaveLength(1);+ expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({+ streamId: firstMeta.streamId,+ seq: firstMeta.seq,});+ expect(replayed.filter((env) => (+ env.kind === 'push'+ && parseTransportPayload(env.payload)+ ))).toHaveLength(0);+ } finally {+ h.client.stop();+ vi.useRealTimers();}- const replayed = firstSocket.sent.slice(sentBefore);- const replays = replayed.filter((env) => (- env.kind === 'invoke-result' && parseTransportPayload(env.payload)- ));- expect(replays).toHaveLength(1);- expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({- streamId: firstMeta.streamId,- seq: firstMeta.seq,- });- expect(replayed.filter((env) => (- env.kind === 'push'- && parseTransportPayload(env.payload)- ))).toHaveLength(0);- h.client.stop();});it('互控:出站 link-accept 不覆盖入站标记,重试耗尽仍走 peer 级重置不拆共享 relay', async () => {diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.tsindex 4fa3c87033..9054da977c 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts@@ -244,7 +244,7 @@ async function startSession(canUseTool?: CanUseToolFn;hooks?: Record<string,- Array<{ hooks: Array<(input: unknown) => Promise<unknown>> }>+ Array<{ matcher?: string; hooks: Array<(input: unknown) => Promise<unknown>> }>>;env?: Record<string, string>;}diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts b/packages/maker-core/src/agents/claude-code/generation-timing.test.tsindex 0d13e49e3a..4f0e0ff31e 100644--- a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts+++ b/packages/maker-core/src/agents/claude-code/generation-timing.test.ts@@ -601,7 +601,9 @@ describe('claude generation pause boundaries', () => {queue.end();const events: AgentEvent[] = [];for await (const event of queue) events.push(event);- const statuses = events.filter((event) => event.type === 'status');+ const statuses = events.filter((event) => event.type === 'status').map((event) => ({+ ...event, data: event.data as { outputTokens?: number; generationDurationMs?: number },+ }));expect(statuses.filter((event) => event.data.outputTokens === 100)).toHaveLength(5);for (const event of statuses.filter((event) => event.data.outputTokens === 100)) {expect(event.data.generationDurationMs).toBe(1_000);diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 01be7d1582..a29c187535 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -3768,7 +3768,7 @@ describe('CodexAgent reference directories', () => {expect(events.filter((event) => event.type === 'done')).toHaveLength(2),);- const doneEvents = events.filter((event): event is Extract<AgentEvent, { type: 'done' }> =>+ const doneEvents = events.filter((event) =>event.type === 'done',);expect((doneEvents[0]?.data as { usage?: { segments?: unknown[] } }).usage?.segments).toHaveLength(1);@@ -5533,7 +5533,7 @@ describe('CodexAgent fast mode service tier', () => {await sendPromise;await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));- const done = events.find((event): event is Extract<AgentEvent, { type: 'done' }> => event.type === 'done');+ const done = events.find((event) => event.type === 'done');expect((done?.data as { usage?: { segments?: unknown[] } }).usage?.segments).toEqual([expect.objectContaining({ inputTokens: 20, outputTokens: 10, priceVariant: 'standard' }),]);@@ -13809,7 +13809,7 @@ describe('CodexAgent MCP thread context hooks', () => {if (!handlers?.mcpServerElicitation) {throw new Error('expected mcpServerElicitation handler');}- handlers.itemStarted({+ handlers.itemStarted!({threadId: 'start-thread-id',turnId: 'turn-wechat-mcp',item: {@@ -13844,7 +13844,7 @@ describe('CodexAgent MCP thread context hooks', () => {toolName: 'mcp:cindy_contacts',suggestions: undefined,});- handlers.itemStarted({+ handlers.itemStarted!({threadId: 'start-thread-id',turnId: 'turn-wechat-mcp',item: {@@ -13871,7 +13871,7 @@ describe('CodexAgent MCP thread context hooks', () => {});expect(resolver.mock.calls[1]?.[0]).not.toHaveProperty('toolUseId');for (const itemId of ['contacts-call-1', 'contacts-call-2']) {- handlers.itemCompleted({+ handlers.itemCompleted!({threadId: 'start-thread-id',turnId: 'turn-wechat-mcp',item: {@@ -13883,7 +13883,7 @@ describe('CodexAgent MCP thread context hooks', () => {},} as never);}- handlers.itemUpdated({+ handlers.itemUpdated!({threadId: 'start-thread-id',turnId: 'turn-wechat-mcp',item: {@@ -23276,7 +23276,7 @@ describe('CodexAgent turn lifecycle', () => {turnStartResponse.resolve({ turn: { id: 'turn-retry-state' } });await sendPromise;} else {- handlers.turnStarted({+ handlers.turnStarted!({threadId: 'start-thread-id',turn: { id: 'turn-retry-state' },});@@ -30530,7 +30530,7 @@ describe('CodexAgent context window reporting', () => {currentTurnResponse.resolve({ turn: { id: 'turn-current-diff' } });await sendPromise;} else {- handlers.turnStarted({+ handlers.turnStarted!({threadId: 'start-thread-id',turn: { id: 'turn-current-diff' },});diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex 218146ed76..654f206699 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -158,7 +158,7 @@ function loadBashPackageHomeHelper(): {target: ts.ScriptTarget.ES2022,},}).outputText;- const context: Record<string, unknown> = {+ const context: Record<string, unknown> & { process: { env: Record<string, string | undefined> } } = {process: { env: {} },path,};diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.tsindex 0933067498..d5dc7a3a10 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts@@ -398,6 +398,7 @@ const timer = setInterval(() => {let files = [];try { files = fs.readdirSync(path.join(config.runDir, 'controls')); } catch {}for (const file of files) {+ if (!file.endsWith('.json')) continue;const control = JSON.parse(fs.readFileSync(path.join(config.runDir, 'controls', file), 'utf8'));if (control.action !== 'stop') continue;clearInterval(timer);@@ -407,6 +408,10 @@ const timer = setInterval(() => {// Publish readiness only after the stop-control poller is installed. Writing// this before setInterval leaves a small CI race where the parent aborts while// this fixture is still initializing and observes only the process exit.+// The writer publishes controls by renaming temporary files. Keep one incomplete+// temporary file present to exercise the reader during that publication window.+fs.mkdirSync(path.join(config.runDir, 'controls'), { recursive: true });+fs.writeFileSync(path.join(config.runDir, 'controls', 'pending.json.tmp-placeholder'), '{');fs.writeFileSync(path.join(config.runDir, 'started'), '1');setTimeout(() => process.exit(2), 5000).unref();`, { mode: 0o700 });diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex ad6e3a8022..fce171be74 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -101,7 +101,7 @@ vi.mock('../rpc-client.js', () => ({}async request(cmd: Record<string, unknown> & { type: string },- ): Promise<{ success: boolean; command?: string; data?: unknown }> {+ ): Promise<{ success: boolean; command?: string; data?: unknown; error?: string }> {captured.requests.push(cmd);if (cmd.type === 'set_model' && captured.holdSetModel) {await captured.holdSetModel;@@ -733,8 +733,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('Pi extension installed')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('Pi extension installed')) {+ visibleReceipt = data.text;break;}}@@ -879,8 +880,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('Installed')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('Installed')) {+ visibleReceipt = data.text;break;}}@@ -1585,7 +1587,8 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {{ type: 'user', content: 'pi install npm:context-mode' },desktopCommandOptions('pi install npm:context-mode'),);- const prompt = captured.requests.find((request) => request.type === 'prompt')?.message ?? '';+ const prompt = captured.requests.find((request) => request.type === 'prompt')?.message;+ if (typeof prompt !== 'string') throw new Error('expected prompt message');expect(prompt).toContain('"ok":true');expect(prompt).toContain('do not claim every task has already stopped');expect(prompt).toContain('this task remains active');@@ -1699,8 +1702,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('context-mode')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('context-mode')) {+ visibleReceipt = data.text;break;}}@@ -1767,8 +1771,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('"name":"extension"')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('"name":"extension"')) {+ visibleReceipt = data.text;break;}}@@ -1832,8 +1837,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('Pi 扩展操作失败。')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('Pi 扩展操作失败。')) {+ visibleReceipt = data.text;break;}}@@ -2084,8 +2090,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('Pi 扩展操作失败。')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('Pi 扩展操作失败。')) {+ visibleReceipt = data.text;break;}}@@ -2262,8 +2269,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {for (let attempt = 0; attempt < 10; attempt += 1) {const event = await events.next();if (event.done) break;- if (event.value.type === 'text' && event.value.data.text.includes('Pi 扩展已安装')) {- visibleReceipt = event.value.data.text;+ const data = event.value.data as { text?: unknown };+ if (event.value.type === 'text' && typeof data?.text === 'string' && data.text.includes('Pi 扩展已安装')) {+ visibleReceipt = data.text;break;}}@@ -2432,7 +2440,8 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {{ type: 'user', content: 'pi install npm:oversized-extension' },desktopCommandOptions('pi install npm:oversized-extension'),);- const prompt = captured.requests.find((request) => request.type === 'prompt')?.message ?? '';+ const prompt = captured.requests.find((request) => request.type === 'prompt')?.message;+ if (typeof prompt !== 'string') throw new Error('expected prompt message');expect(prompt.length).toBeLessThanOrEqual(16_384);expect(prompt).toContain('"name":"oversized-extension"');expect(prompt).toContain('"version":"9.8.7"');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.tsindex 485e9a5769..e8829932bf 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts@@ -363,16 +363,16 @@ describe("PiAgent native auto-compaction ownership", () => {"prompt",(handle: AgentSessionHandle) =>handle.send({- role: "user",- content: [{ type: "text", text: "hi" }],+ type: "user",+ content: "hi",}),],["steer",(handle: AgentSessionHandle) =>handle.steer!({- role: "user",- content: [{ type: "text", text: "steer now" }],+ type: "user",+ content: "steer now",}),],] as const)(@@ -488,7 +488,7 @@ describe("PiAgent native auto-compaction ownership", () => {piAutoCompactThresholdPct: 90,};deps.capabilityAdditions = {- availableModels: deps.capabilityAdditions!.availableModels.map((model) =>+ availableModels: deps.capabilityAdditions!.availableModels!.map((model) =>model.id === "n" ? { ...model, contextWindow: 200_000 } : model,),};diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex e0d8359462..e76441f0bd 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -1021,9 +1021,9 @@ describe('PI durable subagent run store', () => {* until a real signal reaches it, then ESRCH like any reaped process. The* default (never reaped) is the zombie/stubborn case.*/- let sentSignals: Array<NodeJS.Signals | number> = [];+ let sentSignals: Array<NodeJS.Signals | number | 'unknown'> = [];let sentKillPids: number[] = [];- const killSignals = (): Array<NodeJS.Signals | number> => sentSignals;+ const killSignals = (): Array<NodeJS.Signals | number | 'unknown'> => sentSignals;function stubKill(options: { reapedByKill?: boolean } = {}): void {const real = process.kill.bind(process);diff --git a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.tsindex d845d19e7a..2a0e5f0192 100644--- a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts@@ -32,7 +32,7 @@ function makeFakeTransport() {close: vi.fn(async () => { closeHandler?.({ code: 0, signal: null, reason: 'test close' }); }),isClosed: vi.fn(() => false),get pid() { return 1234; },- } as unknown as PiTransport;+ } satisfies PiTransport;const emitLine = (line: string) => lineHandler?.(line);const drain = () => {for (const w of written.splice(0)) w.resolve();@@ -42,7 +42,7 @@ function makeFakeTransport() {function makeProc(overrides: Partial<PiRpcSpawnOptions> = {}) {const logger = {- debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn(),child: () => logger,};const onEvent = vi.fn();@@ -72,7 +72,7 @@ describe('PiRpcProcess response envelope validation', () => {const resp = await p;expect(resp.success).toBe(true);- expect(resp.data?.sessionFile).toBe('/sessions/abc.jsonl');+ expect(resp.data).toMatchObject({ sessionFile: '/sessions/abc.jsonl' });});it('rejects when success is not a boolean (round 40-w4-t4 CRITICAL)', async () => {diff --git a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts b/packages/maker-core/src/agents/pi/__tests__/transport.test.tsindex 9a4a126ed0..f1561065a1 100644--- a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts@@ -9,6 +9,7 @@*/import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));@@ -204,7 +205,7 @@ describe('createPiStdioTransport', () => {describe('attachJsonlReader', () => {function makeStream() {- return new EventEmitter() as EventEmitter & { pipe(): void };+ return new PassThrough();}it('splits lines across chunk boundaries (UTF-8 safe)', () => {diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 2217eff64e..f44970b7ce 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -441,7 +441,7 @@ describe('Maker local Pi package generation fence', () => {it.each([['remote', { remoteHostId: 'ssh-host' }],- ['Review', { reviewMode: true }],+ ['Review', { reviewMode: true as const }],])('does not fence an in-flight %s Pi startup', async (_label, boundary) => {const started = createDeferred<AgentSessionHandle>();const handle = createHandle({ id: 'pi-thread', agentKind: 'pi' });diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex 26f110278f..1d00cc1eba 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -16,7 +16,7 @@ import {type TurnContinuationState,} from './agents/base-agent.js';import type { AgentEvent, InteractionDecision, InteractionRequest, SendOrigin } from './types/events.js';-import type { AgentKind } from './types/common.js';+import type { AgentKind, UserMessage } from './types/common.js';function createLogger() {const logger = {@@ -62,7 +62,7 @@ function createControllableHandle(opts?: {id: 'thread-1',agentKind: opts?.agentKind ?? 'codex',model: 'gpt-5.4',- async send(_message, sendOptions) {+ async send(_message: UserMessage, sendOptions?: SendOptions) {lastSendOptions = sendOptions;sendCount += 1;if (opts?.sendError && (opts.sendErrorOnSend ?? 1) === sendCount) {