Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(mobile): 新建任务沿用上次项目或对话选择 (#3963)

Dashf68ba04649c3
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index e4f06ca3e5..007cd824cf 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -482,7 +482,7 @@ export default function NewRemoteSessionScreen() {
const [draft, setDraft] = useState<NewSessionDraft>({
...DEFAULT_NEW_SESSION_DRAFT,
firstMessage: visualInitialDraft ?? DEFAULT_NEW_SESSION_DRAFT.firstMessage,
- // 默认进入「对话」(无项目),对齐桌面;只有从项目入口带了 workingDir 才默认项目模式。
+ // 无记忆时默认对话;偏好加载后恢复上次选择,显式项目入口优先。
workspaceKind: initialWorkingDir ? 'project' : 'dialogue',
workingDir: initialWorkingDir ?? '',
});
@@ -605,10 +605,13 @@ export default function NewRemoteSessionScreen() {
useEffect(() => {
const stashed = drainStashedNewSessionDraft();
if (!stashed) return;
+ // 返回编辑沿用草稿的工作区,不能被随后加载的全局默认覆盖。
+ userTouchedWorkspaceRef.current = true;
setDraft(stashed.draft);
setAttachments([...stashed.attachments]);
if (stashed.notice) setAttachmentError(stashed.notice);
if (stashed.deviceId) {
+ userTouchedDeviceRef.current = true;
setSelectedDeviceId(stashed.deviceId);
setSelectedDeviceName(stashed.deviceName || stashed.deviceId);
}
@@ -688,6 +691,7 @@ export default function NewRemoteSessionScreen() {
// 权限记忆只在偏好加载后恢复一次(之后由用户选择 / 切 agent 驱动),防止重复覆盖。
const appliedPermissionMemoryRef = useRef(false);
const userTouchedDeviceRef = useRef(false);
+ const userTouchedWorkspaceRef = useRef(false);
const firstMessageRef = useRef(draft.firstMessage);
const firstMessageInputRef = useRef<NativeTextInput>(null);
const voiceDraftScrollRef = useRef<ScrollView>(null);
@@ -827,7 +831,14 @@ export default function NewRemoteSessionScreen() {
setNewSessionPreferencesLoaded(false);
void readNewSessionPreferences()
.then((preferences) => {
- if (!cancelled) setNewSessionPreferences(preferences);
+ if (cancelled) return;
+ setNewSessionPreferences(preferences);
+ const workspaceKind = preferences.workspaceKind;
+ if (!initialWorkingDir && workspaceKind) {
+ setDraft((current) => userTouchedWorkspaceRef.current
+ ? current
+ : { ...current, workspaceKind });
+ }
})
.finally(() => {
if (!cancelled) setNewSessionPreferencesLoaded(true);
@@ -2136,6 +2147,8 @@ export default function NewRemoteSessionScreen() {
}, [patchDraft]);
const selectDialogueWorkspace = useCallback(() => {
+ userTouchedWorkspaceRef.current = true;
+ void saveNewSessionPreferences({ workspaceKind: 'dialogue' });
patchDraft({ workspaceKind: 'dialogue', workingDir: '' });
setWorkspacePickerOpen(false);
setBrowseOpen(false);
@@ -2143,6 +2156,8 @@ export default function NewRemoteSessionScreen() {
}, [patchDraft]);
const selectRecentProject = useCallback((workingDir: string) => {
+ userTouchedWorkspaceRef.current = true;
+ void saveNewSessionPreferences({ workspaceKind: 'project' });
patchDraft({ workspaceKind: 'project', workingDir });
setWorkspacePickerOpen(false);
setBrowseOpen(false);
@@ -2150,6 +2165,8 @@ export default function NewRemoteSessionScreen() {
}, [patchDraft]);
const openProjectBrowse = useCallback(() => {
+ userTouchedWorkspaceRef.current = true;
+ void saveNewSessionPreferences({ workspaceKind: 'project' });
patchDraft({ workspaceKind: 'project' });
setWorkspacePickerOpen(false);
setBrowseOpen(true);
@@ -3667,6 +3684,9 @@ export default function NewRemoteSessionScreen() {
useEffect(() => {
if (!selectedDeviceId || draft.workspaceKind !== 'project' || draft.workingDir.trim()) return;
+ // 恢复项目模式后,等默认设备同步完成再选目录,避免借用上一台电脑的路径。
+ if (!newSessionPreferencesLoaded) return;
+ if (!userTouchedDeviceRef.current && selectedDeviceId !== preferredDefaultDevice?.deviceId) return;
const key = `${selectedDeviceId}:${initialWorkingDir ?? ''}`;
if (initialWorkspaceKeyRef.current === key) return;
@@ -3688,6 +3708,8 @@ export default function NewRemoteSessionScreen() {
loadBrowsePath,
recentWorkspaces,
selectWorkingDir,
+ newSessionPreferencesLoaded,
+ preferredDefaultDevice?.deviceId,
]);
const selectSlashCommand = useCallback((command: MobileSlashCommand) => {
@@ -4075,6 +4097,7 @@ export default function NewRemoteSessionScreen() {
if (!ensureDeviceAlive()) return;
void saveNewSessionPreferences({
agentKind: effectiveDraft.agentKind,
+ workspaceKind: effectiveDraft.workspaceKind,
device: {
deviceId: selectedDeviceId,
name: selectedDeviceName || selectedDeviceId,
@@ -4828,6 +4851,7 @@ export default function NewRemoteSessionScreen() {
}
void saveNewSessionPreferences({
agentKind: draft.agentKind,
+ workspaceKind: draft.workspaceKind,
device: {
deviceId: selectedDeviceId,
name: selectedDeviceName || selectedDeviceId,
diff --git a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
index 873f1b9e55..f393b7cd64 100644
--- a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
+++ b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
@@ -38,6 +38,7 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: 'codex',
device: { deviceId: 'devA', name: 'Mac A' },
+ workspaceKind: null,
permissionModeByAgent: {},
});
expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({
@@ -63,6 +64,7 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: null,
device: { deviceId: 'devB', name: 'devB' },
+ workspaceKind: null,
permissionModeByAgent: {},
});
@@ -70,6 +72,7 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: null,
device: null,
+ workspaceKind: null,
permissionModeByAgent: {},
});
@@ -79,6 +82,7 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: null,
device: { deviceId: 'devC', name: 'devC' },
+ workspaceKind: null,
permissionModeByAgent: {},
});
});
@@ -104,6 +108,7 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: null,
device: null,
+ workspaceKind: null,
permissionModeByAgent: { 'claude-code': 'bypassPermissions', codex: 'ask' },
});
@@ -114,7 +119,62 @@ describe('newSessionPreferenceStore', () => {
await expect(readNewSessionPreferences()).resolves.toEqual({
agentKind: null,
device: null,
+ workspaceKind: null,
permissionModeByAgent: { codex: 'auto' },
});
});
+
+ it('remembers either workspace mode across reloads without losing other preferences', async () => {
+ const { readNewSessionPreferences, saveNewSessionPreferences } =
+ await import('@/session/newSessionPreferenceStore');
+
+ await Promise.all([
+ saveNewSessionPreferences({ workspaceKind: 'project' }),
+ saveNewSessionPreferences({ device: { deviceId: 'devA', name: 'Mac A' } }),
+ saveNewSessionPreferences({ agentKind: 'codex' }),
+ ]);
+ expect(await readNewSessionPreferences()).toMatchObject({
+ workspaceKind: 'project',
+ device: { deviceId: 'devA', name: 'Mac A' },
+ agentKind: 'codex',
+ });
+
+ await Promise.all([
+ saveNewSessionPreferences({ workspaceKind: 'project' }),
+ saveNewSessionPreferences({ workspaceKind: 'dialogue' }),
+ saveNewSessionPreferences({ permissionModeForAgent: { agentKind: 'codex', mode: 'ask' } }),
+ ]);
+ expect(await readNewSessionPreferences()).toMatchObject({
+ workspaceKind: 'dialogue',
+ agentKind: 'codex',
+ permissionModeByAgent: { codex: 'ask' },
+ });
+ });
+
+ it('ignores an unknown workspace mode in old or invalid storage', async () => {
+ const { __testing, readNewSessionPreferences } =
+ await import('@/session/newSessionPreferenceStore');
+ store.set(__testing.storageKey, JSON.stringify({ workspaceKind: 'unknown', agentKind: 'codex' }));
+ expect(await readNewSessionPreferences()).toMatchObject({ workspaceKind: null, agentKind: 'codex' });
+ });
+
+ it('restores the latest choice when the page reopens before saving finishes', async () => {
+ const { readNewSessionPreferences, saveNewSessionPreferences } =
+ await import('@/session/newSessionPreferenceStore');
+ const saving = saveNewSessionPreferences({ workspaceKind: 'project' });
+ const reopened = readNewSessionPreferences();
+ expect(await reopened).toMatchObject({ workspaceKind: 'project' });
+ await saving;
+ });
+
+ it('clears pending selections without letting them restore cleared preferences', async () => {
+ const { clearNewSessionPreferences, readNewSessionPreferences, saveNewSessionPreferences } =
+ await import('@/session/newSessionPreferenceStore');
+ await Promise.all([
+ saveNewSessionPreferences({ workspaceKind: 'project' }),
+ clearNewSessionPreferences(),
+ ]);
+ expect(await readNewSessionPreferences()).toMatchObject({ workspaceKind: null });
+ expect(store.size).toBe(0);
+ });
});
diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
new file mode 100644
index 0000000000..152e9a7dac
--- /dev/null
+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
@@ -0,0 +1,201 @@
+// @vitest-environment jsdom
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { act, createElement, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import ts from 'typescript';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ DEFAULT_NEW_SESSION_DRAFT,
+ buildRecentWorkspaceOptions,
+ pickInitialNewSessionWorkspace,
+ pickNewSessionDefaultDevice,
+ type NewSessionDraft,
+ type NewSessionStoredPreferences,
+ type NewSessionWorkspaceKind,
+} from '@/session/newSession';
+
+// Mount the page's actual workspace hooks in source order, without loading its unrelated
+// voice/media/native UI. Extract AST statements, not copies of the guards under test.
+const source = ts.createSourceFile('new.tsx', readFileSync(
+ resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8',
+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const page = source.statements.find((node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === 'NewRemoteSessionScreen');
+if (!page?.body) throw new Error('NewRemoteSessionScreen not found');
+const declarations = new Set([
+ 'selectedDeviceId', 'selectedDeviceName', 'newSessionPreferences', 'newSessionPreferencesLoaded',
+ 'preferredDefaultDevice', 'recentWorkspaces', 'draft', 'initialWorkspaceKeyRef',
+ 'appliedDefaultDeviceKeyRef', 'userTouchedDeviceRef', 'userTouchedWorkspaceRef',
+ 'patchDraft', 'selectWorkingDir', 'selectDialogueWorkspace', 'selectRecentProject', 'openProjectBrowse',
+]);
+const effectMarkers = new Set([
+ 'drainStashedNewSessionDraft', 'readNewSessionPreferences',
+ 'appliedDefaultDeviceKeyRef', 'pickInitialNewSessionWorkspace',
+]);
+function identifiers(node: ts.Node): Set<string> {
+ const names = new Set<string>();
+ function visit(child: ts.Node) {
+ if (ts.isIdentifier(child)) names.add(child.text);
+ ts.forEachChild(child, visit);
+ }
+ visit(node);
+ return names;
+}
+const selected = page.body.statements.filter((statement) => {
+ if (ts.isVariableStatement(statement)) {
+ const names = statement.declarationList.declarations.flatMap((declaration) =>
+ [...identifiers(declaration.name)]);
+ return names.some((name) => declarations.has(name));
+ }
+ if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)
+ || statement.expression.expression.getText(source) !== 'useEffect') return false;
+ return [...identifiers(statement)].some((name) => effectMarkers.has(name));
+});
+// Fail visibly if a refactor moves/removes a hook; never silently stop exercising it.
+for (const name of [...declarations, ...effectMarkers]) {
+ const matches = selected.filter((node) => ts.isVariableStatement(node)
+ ? node.declarationList.declarations.some((declaration) => identifiers(declaration.name).has(name))
+ : !declarations.has(name) && identifiers(node).has(name));
+ if (matches.length !== 1) throw new Error(`Expected one workspace statement for ${name}`);
+}
+
+interface WorkspaceState {
+ draft: NewSessionDraft;
+ selectedDeviceId: string;
+ newSessionPreferencesLoaded: boolean;
+ selectDialogueWorkspace(): void;
+ selectRecentProject(path: string): void;
+ openProjectBrowse(): void;
+}
+const bindingNames = [
+ 'useState', 'useRef', 'useMemo', 'useEffect', 'useCallback', 'DEFAULT_NEW_SESSION_DRAFT',
+ 'pickNewSessionDefaultDevice', 'buildRecentWorkspaceOptions', 'pickInitialNewSessionWorkspace',
+ 'routeDeviceId', 'routeDeviceName', 'routeDeviceFallback', 'routeDeviceExplicit', 'deviceOptions',
+ 'initialWorkingDir', 'visualInitialDraft', 'sessions', 'readNewSessionPreferences',
+ 'saveNewSessionPreferences', 'drainStashedNewSessionDraft', 'loadBrowsePath', 'setDevicePickerOpen',
+ 'setAttachments', 'setAttachmentError', 'setBrowseOpen', 'setBrowseError',
+ 'setShowHiddenDirectories', 'setWorkspacePickerOpen',
+];
+const compiled = ts.transpileModule(`function usePageWorkspace(bindings) {
+ const { ${bindingNames.join(', ')} } = bindings;
+ ${selected.map((statement) => statement.getText(source)).join('\n')}
+ return { draft, selectedDeviceId, newSessionPreferencesLoaded,
+ selectDialogueWorkspace, selectRecentProject, openProjectBrowse };
+}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+const usePageWorkspace = new Function(`${compiled}; return usePageWorkspace;`)() as
+ (bindings: Record<string, unknown>) => WorkspaceState;
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; });
+
+function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NewSessionWorkspaceKind } = {}) {
+ let resolveRead!: (value: NewSessionStoredPreferences) => void;
+ const pendingRead = new Promise<NewSessionStoredPreferences>((resolve) => { resolveRead = resolve; });
+ const deviceOptions = [{ deviceId: 'a', name: 'A' }, { deviceId: 'b', name: 'B' }];
+ const initialWorkingDir = options.initialWorkingDir ?? null;
+ const bindings = {
+ useState, useRef, useMemo, useEffect, useCallback, DEFAULT_NEW_SESSION_DRAFT,
+ pickNewSessionDefaultDevice, buildRecentWorkspaceOptions,
+ pickInitialNewSessionWorkspace: vi.fn(pickInitialNewSessionWorkspace),
+ routeDeviceId: 'a', routeDeviceName: 'A', routeDeviceFallback: deviceOptions[0],
+ routeDeviceExplicit: !!initialWorkingDir, deviceOptions, initialWorkingDir, visualInitialDraft: null,
+ sessions: deviceOptions.map(({ deviceId }) => ({
+ deviceLinkDeviceId: deviceId, workingDir: `/projects/${deviceId}`, workspaceKind: 'project',
+ status: 'active', updatedAt: '2026-09-01T00:00:00Z',
+ })),
+ readNewSessionPreferences: vi.fn(() => pendingRead),
+ saveNewSessionPreferences: vi.fn(async () => {}),
+ drainStashedNewSessionDraft: vi.fn(() => options.restoredKind ? {
+ draft: { ...DEFAULT_NEW_SESSION_DRAFT, workspaceKind: options.restoredKind,
+ workingDir: options.restoredKind === 'project' ? '/restored/project' : '' },
+ attachments: [], deviceId: 'a', deviceName: 'A',
+ } : null),
+ loadBrowsePath: vi.fn(async () => {}), setDevicePickerOpen: vi.fn(),
+ setAttachments: vi.fn(), setAttachmentError: vi.fn(), setBrowseOpen: vi.fn(),
+ setBrowseError: vi.fn(), setShowHiddenDirectories: vi.fn(), setWorkspacePickerOpen: vi.fn(),
+ };
+ let current!: WorkspaceState;
+ const commits: Array<{ device: string; kind: NewSessionWorkspaceKind; path: string }> = [];
+ function Harness() {
+ current = usePageWorkspace(bindings);
+ useEffect(() => {
+ commits.push({ device: current.selectedDeviceId, kind: current.draft.workspaceKind,
+ path: current.draft.workingDir });
+ });
+ return null;
+ }
+ root = createRoot(document.createElement('div'));
+ act(() => root!.render(createElement(Harness)));
+ return {
+ bindings, commits, get current() { return current; },
+ async resolvePreferences(kind: NewSessionWorkspaceKind | null, deviceId = 'a') {
+ await act(async () => {
+ resolveRead({ workspaceKind: kind, device: { deviceId, name: deviceId },
+ agentKind: null, permissionModeByAgent: {} });
+ await pendingRead;
+ });
+ },
+ };
+}
+
+describe('new session workspace page effects', () => {
+ it('keeps an explicit project entry when a different preference arrives late', async () => {
+ const page = mountWorkspace({ initialWorkingDir: '/explicit/project' });
+ await page.resolvePreferences('dialogue', 'b');
+ expect(page.current.draft).toMatchObject({ workspaceKind: 'project', workingDir: '/explicit/project' });
+ expect(page.current.selectedDeviceId).toBe('a');
+ expect(page.bindings.loadBrowsePath).not.toHaveBeenCalled();
+ });
+
+ it.each(['project', 'dialogue'] as const)('preserves a restored %s draft over a late default', async (kind) => {
+ const page = mountWorkspace({ restoredKind: kind });
+ await page.resolvePreferences(kind === 'project' ? 'dialogue' : 'project', 'b');
+ expect(page.current.draft).toMatchObject({ workspaceKind: kind,
+ workingDir: kind === 'project' ? '/restored/project' : '' });
+ expect(page.current.selectedDeviceId).toBe('a');
+ expect(page.bindings.pickInitialNewSessionWorkspace).not.toHaveBeenCalled();
+ });
+
+ it.each(['project', 'dialogue'] as const)('preserves a manual %s choice made during the read', async (kind) => {
+ const page = mountWorkspace();
+ act(() => kind === 'project'
+ ? page.current.selectRecentProject('/manual/project')
+ : page.current.selectDialogueWorkspace());
+ 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 });
+ });
+
+ it('keeps an explicitly opened project browser open after a late dialogue preference', async () => {
+ const page = mountWorkspace();
+ act(() => page.current.openProjectBrowse());
+ await page.resolvePreferences('dialogue');
+ expect(page.current.draft).toMatchObject({ workspaceKind: 'project', workingDir: '' });
+ expect(page.bindings.setBrowseOpen).toHaveBeenLastCalledWith(true);
+ expect(page.bindings.loadBrowsePath).toHaveBeenCalledExactlyOnceWith('~');
+ });
+
+ it('waits for the remembered device before choosing a project, including intermediate commits', async () => {
+ const page = mountWorkspace();
+ expect(page.current.newSessionPreferencesLoaded).toBe(false);
+ expect(page.bindings.pickInitialNewSessionWorkspace).not.toHaveBeenCalled();
+ await page.resolvePreferences('project', 'b');
+ expect(page.current.selectedDeviceId).toBe('b');
+ expect(page.current.draft.workingDir).toBe('/projects/b');
+ expect(page.bindings.pickInitialNewSessionWorkspace).toHaveBeenCalledTimes(1);
+ expect(page.commits.filter(({ path }) => path)).toEqual([
+ { device: 'b', kind: 'project', path: '/projects/b' },
+ ]);
+ expect(page.bindings.loadBrowsePath).not.toHaveBeenCalled();
+ });
+
+ it('keeps the existing default when storage has no remembered mode', async () => {
+ const page = mountWorkspace();
+ await page.resolvePreferences(null);
+ expect(page.current.draft).toMatchObject({ workspaceKind: 'dialogue', workingDir: '' });
+ expect(page.bindings.pickInitialNewSessionWorkspace).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index d76d73f8a0..2c9e0b64b2 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -76,6 +76,8 @@ export interface NewSessionDeviceOption {
export interface NewSessionStoredPreferences {
agentKind: NewSessionAgentKind | null;
device: NewSessionDeviceOption | null;
+ /** 上次显式选择的项目/对话模式;null 表示尚未选择,沿用入口默认。 */
+ workspaceKind: NewSessionWorkspaceKind | null;
/**
* 每个 agent 上次在新建页显式选过的权限档(对齐桌面 lastByVendor 的权限记忆语义);
* 没选过 = 缺失,回落该 agent 的安全种子默认。'plan' 不入记忆(计划模式是独立开关)。
diff --git a/apps/mobile/src/session/newSessionPreferenceStore.ts b/apps/mobile/src/session/newSessionPreferenceStore.ts
index bd461241ac..edd79dd739 100644
--- a/apps/mobile/src/session/newSessionPreferenceStore.ts
+++ b/apps/mobile/src/session/newSessionPreferenceStore.ts
@@ -4,6 +4,7 @@ import {
type NewSessionAgentKind,
type NewSessionDeviceOption,
type NewSessionStoredPreferences,
+ type NewSessionWorkspaceKind,
} from '@/session/newSession';
const STORAGE_KEY = 'xdt-maker.mobile.new-session.preferences.v1';
@@ -11,11 +12,18 @@ const STORAGE_KEY = 'xdt-maker.mobile.new-session.preferences.v1';
export interface NewSessionPreferencePatch {
agentKind?: NewSessionAgentKind;
device?: NewSessionDeviceOption;
+ workspaceKind?: NewSessionWorkspaceKind;
/** 记住某 agent 在新建页选的权限档(单键合并进 permissionModeByAgent;'plan' 被忽略)。 */
permissionModeForAgent?: { agentKind: NewSessionAgentKind; mode: string };
}
export async function readNewSessionPreferences(): Promise<NewSessionStoredPreferences> {
+ // 刚选完就重新打开新建页时,也要看到已提交但尚未落盘的选择。
+ await writeChain;
+ return loadNewSessionPreferences();
+}
+
+async function loadNewSessionPreferences(): Promise<NewSessionStoredPreferences> {
const raw = await AsyncStorage.getItem(STORAGE_KEY).catch(() => null);
if (!raw) return emptyPreferences();
try {
@@ -25,11 +33,21 @@ export async function readNewSessionPreferences(): Promise<NewSessionStoredPrefe
}
}
-export async function saveNewSessionPreferences(patch: NewSessionPreferencePatch): Promise<void> {
- const current = await readNewSessionPreferences();
+// 与首页偏好存储一致:连续选择不同字段时,读改写必须按操作顺序执行。
+let writeChain: Promise<void> = Promise.resolve();
+
+export function saveNewSessionPreferences(patch: NewSessionPreferencePatch): Promise<void> {
+ const next = writeChain.then(() => writeNewSessionPreferences(patch));
+ writeChain = next.catch(() => undefined);
+ return next;
+}
+
+async function writeNewSessionPreferences(patch: NewSessionPreferencePatch): Promise<void> {
+ const current = await loadNewSessionPreferences();
const permissionPatch = patch.permissionModeForAgent;
const next: NewSessionStoredPreferences = {
agentKind: patch.agentKind ?? current.agentKind,
+ workspaceKind: patch.workspaceKind ?? current.workspaceKind,
device: patch.device
? normalizeDeviceOption(patch.device)
: current.device,
@@ -41,13 +59,16 @@ export async function saveNewSessionPreferences(patch: NewSessionPreferencePatch
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(serializePreferences(next))).catch(() => undefined);
}
-export async function clearNewSessionPreferences(): Promise<void> {
- await AsyncStorage.removeItem(STORAGE_KEY).catch(() => undefined);
+export function clearNewSessionPreferences(): Promise<void> {
+ const next = writeChain.then(() => AsyncStorage.removeItem(STORAGE_KEY));
+ writeChain = next.catch(() => undefined);
+ return writeChain;
}
function emptyPreferences(): NewSessionStoredPreferences {
return {
agentKind: null,
+ workspaceKind: null,
device: null,
permissionModeByAgent: {},
};
@@ -78,6 +99,9 @@ function normalizeStoredPreferences(value: unknown): NewSessionStoredPreferences
const deviceName = readString(record.deviceName);
return {
agentKind: normalizeNewSessionAgentKind(record.agentKind),
+ workspaceKind: record.workspaceKind === 'project' || record.workspaceKind === 'dialogue'
+ ? record.workspaceKind
+ : null,
device: deviceId
? { deviceId, name: deviceName || deviceId }
: null,
@@ -102,6 +126,7 @@ function serializePreferences(
);
return {
...(preferences.agentKind ? { agentKind: preferences.agentKind } : {}),
+ ...(preferences.workspaceKind ? { workspaceKind: preferences.workspaceKind } : {}),
...(preferences.device
? {
deviceId: preferences.device.deviceId,