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。

refactor: organize session workflow boundaries and developer guidance

Dash75089bf71136
diff --git a/AGENTS.md b/AGENTS.md
index b64cd2bb8e..269d7129ec 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,6 +20,18 @@
- 目录或模块专属规则优先放到对应目录的嵌套 `AGENTS.md`;需要跨目录复用的
专题说明放在 `docs/`,并由本文件写明触发条件。
+## 按模块进入
+
+开发、启动、调试或验证对应模块前,先读下表入口,再按改动触发条件读专题;根级规则始终适用。
+跨模块行为先从[仓库地图的行为导航](docs/dev-rules/repo-map.md#按用户行为定位)查找公共入口与测试,
+不要只修改最先找到的页面或渠道。
+
+| 修改范围 | 模块规则入口 | 开发与架构正本 |
+| --- | --- | --- |
+| Desktop:main、renderer、preload、数据库、个人 IM / 官方 hook | [apps/desktop/AGENTS.md](apps/desktop/AGENTS.md) | [Desktop 开发](docs/dev-rules/desktop-development.md) |
+| Mobile:Expo 页面、远程调用、原生配置与模块 | [apps/mobile/AGENTS.md](apps/mobile/AGENTS.md) | [Mobile 开发与冷更边界](docs/dev-rules/mobile-development.md) |
+| maker-core:Agent 编排、prompt、工具、translator、用量 | [packages/maker-core/AGENTS.md](packages/maker-core/AGENTS.md) | [Agent 行为](docs/dev-rules/maker-core-and-agent-behavior.md) |
+
## 当前规则索引
- 首次接触本仓、需要定位功能代码位置或判断新代码归属模块时,先读仓库地图
@@ -30,26 +42,10 @@
或排查目录下发与显示错误前,必须先读 `docs/dev-rules/model-catalog-maintenance.md`:
先看结构、覆盖顺序与修改位置,再按其中导航读取专题规则和实际代码;Server 正本与客户端
离线副本需协调更新,客户端已支持、Server 已实现和生产已部署必须分别核验。
-- 启动、调试或验证 Desktop 时,必须先读 `docs/dev-rules/desktop-development.md`。
-- 修改 Desktop Renderer、preload、BrowserWindow、WebView、IPC、CSP、导航或 Electron
- 特权能力前,必须先读 `docs/dev-rules/electron-security-and-process-boundaries.md`。
-- 新增或修改 Desktop 独立窗口、辅助窗口或弹出型 `BrowserWindow` 前,必须遵守
- `docs/dev-rules/electron-security-and-process-boundaries.md` 的「独立辅助窗口统一生命周期
- 基线」:复用既有控制器/基础设施,不得另造平行的预热、就绪握手、隐藏复用与崩溃恢复
- 状态机。
- 修改凭证或授权信息处理、文件落盘位置、用户持久数据、临时文件或测试目录前,必须
先读 `docs/dev-rules/credentials-and-local-storage.md`。
- 新增或修改媒体生成、导入、缓存、附件、持久化、协议解析或回收逻辑前,必须先读
`docs/dev-rules/media-storage-and-protocols.md`。
-- 修改 Desktop 数据库 schema、migration、companion script 或运行期数据库访问前,必须
- 先读 `docs/dev-rules/database-and-migrations.md`。
-- 开发、调试或验证 Mobile 时,必须先读 `docs/dev-rules/mobile-development.md`。
-- 修改 `apps/mobile` 的原生配置、原生依赖、config plugin 或原生模块(`app.json`、
- `app.config.js`、`eas.json`、`apps/mobile/package.json`、`plugins/`、`modules/` 等会
- 进入 runtime fingerprint 的输入)前,必须先读 `docs/dev-rules/mobile-development.md`
- 的「冷更边界」:**除非必要,不得提交会改变指纹的改动**;会触发冷更的 PR 与技术框架
- 变动同级,必须由仓库指定的把关人针对冷更明确确认后才能合并——不看改动大小,也不看谁
- 提的,提交者身份不构成例外。
- 新增或调整产品功能、判断能力应进入 Core / Skill / 插件、设计人机交互或多端体验
前,必须先读 `docs/product-rules/core-product-principles.md`。
- 新增或修改 Agent 管理用户自己的任务、定时任务、项目、伙伴的工具(`cindy_helper` /
@@ -92,15 +88,6 @@
- 新增或修改任何界面、组件、布局、样式、动效或 UI 文案前,必须先读权威设计规范
`docs/design-rules/DESIGN.md`;设计文档索引见
`docs/design-rules/cindy-design-system.md`。
-- 改完 Desktop renderer 界面(组件、样式、布局、文案、深浅色、多语言)后自检,先运行
- `pnpm ui:check --changed --theme all` 并查看输出的 `overview.png`,无需为此启动完整
- Desktop;输出中 `UNCOVERED` 的文件未被验证。发 PR 时运行 `pnpm ui:check:publish`,把输出的
- 带图内容写进「UI 变化」。按改动类型选择验证方式见
- `docs/dev-rules/desktop-development.md`「按改动选择验证方式」。
-- 新增或修改 Mobile(`apps/mobile`)界面上的文字前,必须先查
- `apps/mobile/docs/mobile-design-guide.md` §3「文字规范速查」:先定角色,再整行照抄字号、
- 行高、字重、字色;五档中性字色、浅色字不配粗字重、11 档字号、必须配行高四条由
- `typographyTokenDiscipline.test.ts` 守护,角色是否选对靠 review。
- 做 UI 圆角分类或点击目标尺寸审查时,必须同时读 `docs/design-rules/DESIGN.md §5` 与
`docs/design-rules/design-governance.md §13`;普通 UI 改动同样适用,不限于设计系统迁移 PR。
- 新增或修改设计 Token、主题系统、标准 UI 组件(primitive / pattern)、视觉类门禁脚本,
@@ -111,9 +98,6 @@
的术语照用,不自造译法;表里没有或拿不准的,在 `i18n/glossary.json` 加
`status: "proposed"` 条目再讨论。门禁为 `pnpm check:i18n-glossary`,规则见
`docs/dev-rules/engineering-conventions.md` §5.1。
-- 修改个人 IM 渠道(`apps/desktop/src/main/im/**`)或官方 hook(`hook-control/**`)的
- 找/建任务、命令、排队与插话、输入拼装、事件观察、交互、收尾或停止逻辑前,必须先读
- `docs/dev-rules/im-turn-flow.md`(入口账本、状态清单、不变量与迁移批次)。
- 新增或修改**任一 Telegram bot 的用户可见行为**(命令、消息呈现、收口策略、群行为、
权限口径、附件与表情)前,必须先读能力台账 `docs/product-rules/telegram-bot-parity.md`:
两个 bot 是两套架构,差异可以有但必须登记在表里;表里标「有意不同」的行**不要去
@@ -129,8 +113,7 @@
为准。
- 修改 Orca 多 Agent 协同时,必须先读
`docs/dev-rules/orca-team-architecture.md`。
-- 修改 `packages/maker-core` 的 Agent 编排、prompt 组装、tool/MCP 暴露、translator、
- model 映射、usage 计量,或任何进入模型 system 段的提示词前,必须先读
+- 修改任何进入模型 system 段的提示词前(无论文件位于哪个模块),必须先读
`docs/dev-rules/maker-core-and-agent-behavior.md`。
- 修改 PI harness 集成(`packages/maker-core/src/agents/pi/**`、`pi-host.ts`、
`piEnvironment.ts`)、PI 会话权限/配置/system prompt/桥接,或 PI 相关的上线判断前,
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
new file mode 100644
index 0000000000..ad869285da
--- /dev/null
+++ b/apps/desktop/AGENTS.md
@@ -0,0 +1,28 @@
+# Desktop:Agent 工作入口
+
+本文件适用于 `apps/desktop/`;[根 AGENTS](../../AGENTS.md) 的跨仓、数据、授权、
+插件兼容、协议与交付规则仍然适用。本文只维护模块触发条件,专题正文继续使用同一正本。
+代码、共享判据与测试入口见[仓库地图](../../docs/dev-rules/repo-map.md#按用户行为定位)。
+
+## 开发与进程边界
+
+- 启动、调试或验证 Desktop 时,必须先读[Desktop 开发](../../docs/dev-rules/desktop-development.md)。
+- 修改 Desktop Renderer、preload、BrowserWindow、WebView、IPC、CSP、导航或 Electron
+ 特权能力前,必须先读[Electron 安全与进程边界](../../docs/dev-rules/electron-security-and-process-boundaries.md)。
+- 新增或修改 Desktop 独立窗口、辅助窗口或弹出型 `BrowserWindow` 前,必须遵守
+ [Electron 安全与进程边界](../../docs/dev-rules/electron-security-and-process-boundaries.md)的「独立辅助窗口统一生命周期
+ 基线」:复用既有控制器/基础设施,不得另造平行的预热、就绪握手、隐藏复用与崩溃恢复
+ 状态机。
+- 修改 Desktop 数据库 schema、migration、companion script 或运行期数据库访问前,必须
+ 先读[数据库与迁移](../../docs/dev-rules/database-and-migrations.md)。
+
+## 界面与渠道
+
+- 改完 Desktop renderer 界面(组件、样式、布局、文案、深浅色、多语言)后自检,先运行
+ `pnpm ui:check --changed --theme all` 并查看输出的 `overview.png`,无需为此启动完整
+ Desktop;输出中 `UNCOVERED` 的文件未被验证。发 PR 时运行 `pnpm ui:check:publish`,把输出的
+ 带图内容写进「UI 变化」。按改动类型选择验证方式见
+ [Desktop 开发](../../docs/dev-rules/desktop-development.md)「按改动选择验证方式」。
+- 修改个人 IM 渠道(`src/main/im/**`)或官方 hook(`src/main/hook-control/**`)的
+ 找/建任务、命令、排队与插话、输入拼装、事件观察、交互、收尾或停止逻辑前,必须先读
+ [IM 轮次流程](../../docs/dev-rules/im-turn-flow.md)(入口账本、状态清单、不变量与迁移批次)。
diff --git a/apps/mobile/AGENTS.md b/apps/mobile/AGENTS.md
new file mode 100644
index 0000000000..0a08a59591
--- /dev/null
+++ b/apps/mobile/AGENTS.md
@@ -0,0 +1,17 @@
+# Mobile:Agent 工作入口
+
+本文件适用于 `apps/mobile/`;[根 AGENTS](../../AGENTS.md) 的数据、授权、跨端协议、
+产品、设计与交付规则仍然适用。代码、共享判据与测试入口见
+[仓库地图](../../docs/dev-rules/repo-map.md#按用户行为定位)。
+
+- 开发、调试或验证 Mobile 时,必须先读[Mobile 开发](../../docs/dev-rules/mobile-development.md)。
+- 修改本模块的原生配置、原生依赖、config plugin 或原生模块(`app.json`、
+ `app.config.js`、`eas.json`、`package.json`、`plugins/`、`modules/` 等会
+ 进入 runtime fingerprint 的输入)前,必须先读[Mobile 开发](../../docs/dev-rules/mobile-development.md)
+ 的「冷更边界」:**除非必要,不得提交会改变指纹的改动**;会触发冷更的 PR 与技术框架
+ 变动同级,必须由仓库指定的把关人针对冷更明确确认后才能合并——不看改动大小,也不看谁
+ 提的,提交者身份不构成例外。
+- 新增或修改 Mobile 界面上的文字前,必须先查
+ [Mobile 设计指南](docs/mobile-design-guide.md) §3「文字规范速查」:先定角色,再整行照抄字号、
+ 行高、字重、字色;五档中性字色、浅色字不配粗字重、11 档字号、必须配行高四条由
+ `typographyTokenDiscipline.test.ts` 守护,角色是否选对靠 review。
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index b74596ccca..3adc955945 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -1,3 +1,34 @@
+import {
+ reconcileNewSessionCatalogDraft,
+ reconcileNewSessionSubmitDraft,
+ revalidateNewSessionDraftAfterAuth,
+ restoreNewSessionFastPreference,
+} from '@/session/newSessionRuntimeReconciliation';
+import { useNewSessionWorktreeSync } from '@/session/useNewSessionWorktreeSync';
+import {
+ publishNewSessionVoiceDraft,
+ changeNewSessionVoiceText,
+ changeNewSessionVoiceSelection,
+ finishNewSessionVoiceRecording,
+ newSessionVoiceComposerProps,
+} from '@/session/newSessionVoiceInput';
+import { prepareNewSessionCreation } from '@/session/prepareNewSessionCreation';
+import {
+ appendNewSessionSharedText,
+ openNewSessionPluginPalette,
+ captureNewSessionOwner,
+ createInitialNewSessionDraft,
+ markNewSessionIncomingShare,
+ patchNewSessionDraft,
+ restoreNewSessionDraft,
+ setNewSessionFirstMessage,
+} from '@/session/newSessionForm';
+import {
+ useNewSessionStashedDraft,
+ useNewSessionWorkspacePreferences,
+ useNewSessionWorkspaceActions,
+ useNewSessionInitialWorkspace,
+} from '@/session/useNewSessionWorkspace';
import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';
import { ModelSpeedIcon } from '@/session/ModelSpeedIcon';
import { useNewSessionHostDefaults } from '@/session/useNewSessionHostDefaults';
@@ -6,13 +37,11 @@ import { useNewSessionDefaultSelection } from '@/session/useNewSessionDefaultSel
import { parseGoalCommand } from '@cindy/maker-shared/goal-command';
import { mergeMobileGoalCommand, parseMobileDesktopCommand } from '@/session/desktopSlashCommands';
import { modelNeedsReselection } from '@/session/modelReselection';
-import { isCindyAutoModelId } from '@cindy/model-providers/provider-identity';
+
import { completePrecreatedWorktreeRecovery } from '@/session/completePrecreatedWorktreeRecovery';
-import { outboxCreationRetryIdentity } from '@/session/cancelledCreationDraft';
-import { isRemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';
+
import { mobileDurableOutbox, getCurrentMobileOutboxRecords } from '@/session/mobileDurableOutbox';
-import { persistNewSessionCreationDraft } from '@/session/persistNewSessionCreationDraft';
-import { buildOutboxItem, createOutboxClientId } from '@/session/sessionOutbox';
+
import type { DurableOutboxRecord } from '@/session/durableOutbox';
import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
import { workspacePathsEqual } from '@/session/workspaceSelection';
@@ -78,7 +107,6 @@ import {
Target,
UsersRound,
X,
- Zap,
} from 'lucide-react-native';
import {
getRecordingPermissionsAsync,
@@ -113,11 +141,10 @@ import {
} from '@/session/agentCapabilities';
import {
MOBILE_MAX_ATTACHMENTS,
- attachmentDisplayLabel,
} from '@/session/attachments';
import { useAuth } from '@/auth/AuthContext';
import { discardMobileUploadedAttachment } from '@/session/mobileAttachmentUpload';
-import { discardNewSessionUploadedAttachments } from '@/session/newSessionAttachmentCleanup';
+import { clearNewSessionAttachmentsForDeviceChange, discardNewSessionUploadedAttachments } from '@/session/newSessionAttachmentCleanup';
import { useAutoResumeNewSessionDraft, useNewSessionDurableEdit } from '@/session/useNewSessionDraftRecovery';
import { goBackGuarded } from '@/utils/backGuard';
import { buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttachment';
@@ -149,7 +176,7 @@ import {
ContextSheetRow,
} from '@/session/ContextSheet';
import { ComposerPluginPalette, ContextSheetPlugins } from '@/session/ContextSheetPlugins';
-import { appendComposerPluginTrigger, detectComposerPluginTrigger, placeComposerPlugin } from '@/session/composerPlugins';
+import { detectComposerPluginTrigger, placeComposerPlugin } from '@/session/composerPlugins';
import type { ComposerPlugin } from '@/session/remoteComposerPlugins';
import { textComposerDocument, composerDocumentProjectedText } from '@/session/composerDocument';
import { OrcaWorkerFormView } from '@/session/ContextSheetCollabView';
@@ -160,7 +187,6 @@ import {
describeOrcaError,
enableOrcaTeam,
isOrcaCollabEligible,
- orcaAgentLabel,
orcaCollabEntryHint,
narrowOrcaWorkerProvider,
orcaCollabDraftTargetKey,
@@ -201,8 +227,6 @@ import {
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import {
applyRemoteAgentPick,
- assertSubmitModelResolved,
- DEFAULT_NEW_SESSION_DRAFT,
NEW_SESSION_AGENT_OPTIONS,
availableNewSessionAgentOptions,
defaultPermissionModeForNewSessionAgent,
@@ -217,18 +241,14 @@ import {
isNewSessionDraftMissingPayloadOnly,
parseNewSessionDeviceOptions,
pickAgentDefaultRuntime,
- pickInitialNewSessionWorkspace,
pickNewSessionDefaultDevice,
sessionFromCreateResult,
compensatePrecreatedWorktree,
- reconcileEffortAfterFallback,
- resolveRecentModelAndProvider,
resolveStartedDowngradeOrCommit,
resolveSubmitGuardCatalog,
validateNewSessionDraft,
type SubmitGuardCatalog,
type NewSessionAgentKind,
- type NewSessionRuntime,
type NewSessionDraft,
type NewSessionDeviceOption,
type NewSessionRemoteAgentPick,
@@ -241,14 +261,12 @@ import { i18n } from '@/i18n';
import {
getMobileAuthOwner,
subscribeMobileAuthOwner,
- isMobileAuthOwnerCurrent,
} from '@/auth/authOwnerGeneration';
import { useTranslation } from 'react-i18next';
import {
createNewSessionId,
drainStashedNewSessionDraft,
hasLiveNewSessionCreation,
- holdNewSessionCreationDraft,
startNewSessionCreation,
} from '@/session/newSessionCreation';
import {
@@ -261,13 +279,11 @@ import {
} from '@/session/precreatedWorktreeRecovery';
import { prepareMobileQueuedSessionReferences } from '@/session/sessionReferences';
import {
- readNewSessionPreferences,
saveNewSessionPreferences,
} from '@/session/newSessionPreferenceStore';
import {
remoteSessionStore,
useRemoteNewMakerWorktreeBranchPreference,
- useRemoteNewMakerWorktreePreference,
useRemoteSessions,
} from '@/session/remoteSessionStore';
import { buildSessionComposerLayout } from '@/session/sessionComposerLayout';
@@ -377,9 +393,7 @@ import { SheetModal } from '@/session/SheetModal';
import { SheetSurface } from '@/session/SheetSurface';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import {
- applyWorktreePreferenceOnHost,
buildWorktreeCreateRequest,
- classifyWorktreePreferenceSeed,
formatWorktreeCreateFailure,
isExactRemoteSessionClaimed,
isValidWorktreeBranchPreferenceSnapshot,
@@ -388,11 +402,9 @@ import {
initialWorktreeProbeEligibility,
resolveWorktreeEligibility,
shouldAcceptWorktreeBranchListResult,
- shouldBlockNewSessionCreateForWorktree,
settleWorktreeEligibilityForDisplay,
shouldShowWorktreeToggle,
worktreeEligibilityForTarget,
- worktreeEligibilityCaptionKey,
worktreeEligibilityFromError,
worktreeSourceBranchFromPreference,
type NewSessionWorktreeEligibility,
@@ -445,19 +457,6 @@ interface WorktreeBranchListSnapshot {
failed: boolean;
}
-interface WorktreePreferenceWriteTransaction {
- seq: number;
- deviceId: string;
- enabled: boolean;
- revisionAtStart: number;
- status: 'writing' | 'reconciling' | 'committed';
-}
-
-interface PendingWorktreePreferenceAuthority {
- enabled: boolean;
- revisionAtStart: number;
-}
-
interface WorktreeBranchPreferenceWriteTransaction {
seq: number;
key: string;
@@ -471,16 +470,6 @@ interface WorktreeBranchCompatibilitySelection {
sourceBranch: string;
}
-interface WorktreeCreateIntentSnapshot {
- applicable: boolean;
- enabled: boolean;
- target: { deviceId: string; workingDir: string };
- eligibility: NewSessionWorktreeEligibility;
- sourceBranch: string;
- branchPreferenceKey: string;
- branchPreferenceSyncKey: string;
-}
-
export default function NewRemoteSessionScreen() {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -580,15 +569,6 @@ export default function NewRemoteSessionScreen() {
);
const selectedDeviceLabel = selectedDeviceOption?.name || selectedDeviceName || selectedDeviceId || t('session.new.selectDevice');
const maker = useMobileMakerTransport(selectedDeviceId);
- const worktreePreference = useRemoteNewMakerWorktreePreference(selectedDeviceId);
- // Defaults are advisory. A choice made in this draft wins over later host pushes.
- const worktreeChoicesRef = useRef(new Map<string, boolean>());
- const [, setWorktreeChoiceVersion] = useState(0);
- const worktreeEnabled = (selectedDeviceId
- ? worktreeChoicesRef.current.get(selectedDeviceId)
- : undefined) ?? worktreePreference.enabled;
- const worktreeEnabledRef = useRef(worktreeEnabled);
- worktreeEnabledRef.current = worktreeEnabled;
const sessions = useRemoteSessions();
const recentWorkspaces = useMemo(
() => buildRecentWorkspaceOptions(
@@ -597,15 +577,9 @@ export default function NewRemoteSessionScreen() {
),
[selectedDeviceId, sessions],
);
- const [draft, setDraft] = useState<NewSessionDraft>({
- ...DEFAULT_NEW_SESSION_DRAFT,
- firstMessage: visualInitialDraft ?? readRouteString(params.draft) ?? (isRemoteTaskSuggestionId(params.suggestion)
- ? t(`devices.list.taskSuggestions.items.${params.suggestion}.prompt`)
- : DEFAULT_NEW_SESSION_DRAFT.firstMessage),
- // 无记忆时默认对话;偏好加载后恢复上次选择,显式项目入口优先。
- workspaceKind: initialWorkingDir ? 'project' : 'dialogue',
- workingDir: initialWorkingDir ?? '',
- });
+ const [draft, setDraft] = useState<NewSessionDraft>(() => createInitialNewSessionDraft({
+ initialWorkingDir, visualInitialDraft, routeDraft: params.draft, suggestion: params.suggestion, t,
+ }));
const firstMessageRef = useRef(draft.firstMessage);
const [planModeDraftOn, setPlanModeDraftOn] = useState(false);
const prePlanPermissionModeRef = useRef<string | null>(null);
@@ -790,24 +764,6 @@ export default function NewRemoteSessionScreen() {
const worktreeEligibilityRef = useRef<NewSessionWorktreeEligibility>({ status: 'probing' });
const worktreeSettledRef = useRef<NewSessionWorktreeSettledSnapshot | null>(null);
const worktreeSourceBranchRef = useRef('HEAD');
- const worktreeSeedSeqRef = useRef(0);
- const [worktreeSeedRetryNonce, setWorktreeSeedRetryNonce] = useState(0);
- const worktreePreferenceSyncKeyRef = useRef('');
- const worktreePreferenceWriteSeqRef = useRef(0);
- // Serialize writes of the next default independently of the current draft.
- const worktreePreferenceWriteTargetRef = useRef<string | null>(null);
- const [worktreePreferenceSavingDeviceId, setWorktreePreferenceSavingDeviceId] =
- useState<string | null>(null);
- const worktreePreferenceTransactionRef = useRef<WorktreePreferenceWriteTransaction | null>(null);
- const worktreePreferenceRenderedRef = useRef({
- deviceId: selectedDeviceId,
- enabled: worktreeEnabled,
- revision: worktreePreference.revision,
- });
- const worktreePreferenceAuthorityUnknownByDeviceRef = useRef(
- new Map<string, PendingWorktreePreferenceAuthority>(),
- );
- const [, setWorktreePreferenceAuthorityVersion] = useState(0);
const [attachments, setAttachments] = useState<RemoteSerializedAttachment[]>([]);
// create() 里 await 在途图片上传后闭包里的 attachments 已是旧值,经 ref 读最新列表。
const attachmentsRef = useRef(attachments);
@@ -826,34 +782,34 @@ export default function NewRemoteSessionScreen() {
// (创建期间发出的消息可能超出单条上限,装不下的只能丢,但不能静默丢,review P1)。
// 声明在 attachmentError 之后:notice 就落在附件错误行上。
const outboxRecoveryRef = useRef<DurableOutboxRecord | null>(null);
+ const userTouchedDeviceRef = useRef(false);
const restoreCreationDraft = useCallback((
saved: NewSessionDraft,
files: RemoteSerializedAttachment[],
plan?: { enabled: boolean; restorePermissionMode: string | null },
controlledDeviceId?: string,
) => {
- // 存下来的草稿里 Agent 在另一台电脑时,模型属于那台:拆回远程选择,草稿本身回到被控电脑。
- const { agentDeviceId, ...recovered } = saved;
- setRemoteAgentChoice(agentDeviceId && controlledDeviceId ? {
+ restoreNewSessionDraft(
+ {
+ setRemoteAgentChoice,
+ userTouchedWorkspaceRef,
+ userTouchedRuntimeRef,
+ appliedPermissionMemoryRef,
+ runtimeActionSeqRef,
+ firstMessageRef,
+ firstMessageSelectionRef,
+ setFirstMessageSelection,
+ attachmentsRef,
+ setAttachments,
+ setPlanModeDraftOn,
+ prePlanPermissionModeRef,
+ setDraft,
+ },
+ saved,
+ files,
+ plan,
controlledDeviceId,
- pick: { deviceId: agentDeviceId, agentKind: saved.agentKind, model: saved.model,
- providerId: saved.providerId, effort: saved.effort, fastMode: saved.fastMode },
- } : null);
- userTouchedWorkspaceRef.current = true;
- userTouchedRuntimeRef.current = true;
- appliedPermissionMemoryRef.current = true;
- runtimeActionSeqRef.current += 1;
- firstMessageRef.current = recovered.firstMessage;
- const selection = { start: recovered.firstMessage.length, end: recovered.firstMessage.length };
- firstMessageSelectionRef.current = selection;
- setFirstMessageSelection(selection);
- attachmentsRef.current = files;
- setAttachments(files);
- if (plan) {
- setPlanModeDraftOn(plan.enabled);
- prePlanPermissionModeRef.current = plan.restorePermissionMode;
- }
- setDraft(recovered);
+ );
}, []);
const leaveForeignOutboxRecovery = useCallback(() => {
const record = outboxRecoveryRef.current;
@@ -885,25 +841,24 @@ export default function NewRemoteSessionScreen() {
setSelectedDeviceName(record.creation.deviceName);
},
});
- useEffect(() => {
- const stashed = drainStashedNewSessionDraft(readRouteString(params.editSessionId) ?? undefined, routeDeviceId);
- if (!stashed) return;
- restoreCreationDraft(stashed.draft, [...stashed.attachments], undefined, stashed.deviceId || undefined);
- if (stashed.notice) setAttachmentError(stashed.notice);
- if (stashed.collabDraft && stashed.deviceId) {
+ useNewSessionStashedDraft({
+ sessionId: readRouteString(params.editSessionId) ?? undefined,
+ deviceId: routeDeviceId,
+ drainStashedNewSessionDraft,
+ restoreCreationDraft,
+ setAttachmentError,
+ userTouchedDeviceRef,
+ setSelectedDeviceId,
+ setSelectedDeviceName,
+ onRestoreCollab: (stashed) => {
collabDraftTargetRef.current = orcaCollabDraftTargetKey(
- stashed.deviceId,
+ stashed.deviceId!,
stashed.draft.workspaceKind,
stashed.draft.workingDir,
);
setCollabDraft(stashed.collabDraft);
- }
- if (stashed.deviceId) {
- userTouchedDeviceRef.current = true;
- setSelectedDeviceId(stashed.deviceId);
- setSelectedDeviceName(stashed.deviceName || stashed.deviceId);
- }
- }, [params.editSessionId, routeDeviceId, restoreCreationDraft]);
+ },
+ });
// 圈点标注接线 api 的 ref 中转(同会话页):hook 实例声明在 removeAttachment
// 之后,onUploaded 等回调延迟执行经 ref 读最新实例。
const composerAnnotationsRef = useRef<UseComposerImageAnnotationsResult | null>(null);
@@ -964,7 +919,7 @@ export default function NewRemoteSessionScreen() {
}), [auth.getAccessToken, discardAllPendingUploads]);
const incomingShareBatch = useIncomingShareBatch();
const incomingShareReceivedRef = useRef(false);
- if (incomingShareBatch?.destination === 'new') incomingShareReceivedRef.current = true;
+ markNewSessionIncomingShare(incomingShareBatch, incomingShareReceivedRef);
const isShareTargetFocused = useIsFocused();
useAutoResumeNewSessionDraft({
enabled: !(params.recoverySessionId || params.editSessionId || params.draft || params.suggestion
@@ -1013,7 +968,6 @@ export default function NewRemoteSessionScreen() {
const appliedDefaultDeviceKeyRef = useRef<string | null>(null);
// 权限记忆只在偏好加载后恢复一次(之后由用户选择 / 切 agent 驱动),防止重复覆盖。
const appliedPermissionMemoryRef = useRef(false);
- const userTouchedDeviceRef = useRef(false);
const userTouchedWorkspaceRef = useRef(false);
const firstMessageInputRef = useRef<NativeTextInput>(null);
const composerPillOpen = useComposerPillOpen(composerDock.enabled, () => firstMessageInputRef.current?.focus());
@@ -1247,59 +1201,26 @@ export default function NewRemoteSessionScreen() {
agentKind: draft.agentKind,
hasFastModeCap: capabilities?.hasFastMode === true,
});
- useEffect(() => {
- let cancelled = false;
- setNewSessionPreferencesLoaded(false);
- void readNewSessionPreferences()
- .then((preferences) => {
- if (cancelled) return;
- // 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
- ? current
- : { ...current, workspaceKind });
- }
- })
- .finally(() => {
- if (!cancelled) setNewSessionPreferencesLoaded(true);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- useEffect(() => {
- if (!newSessionPreferencesLoaded) return;
- if (userTouchedDeviceRef.current) return;
- const key = [
- routeDeviceId,
- routeDeviceName,
- initialWorkingDir ?? '',
- routeDeviceExplicit ? 'explicit' : 'default',
- newSessionPreferences?.device?.deviceId ?? '',
- deviceOptions.map((option) => option.deviceId).join(','),
- ].join('|');
- if (appliedDefaultDeviceKeyRef.current === key) return;
- appliedDefaultDeviceKeyRef.current = key;
- setSelectedDeviceId(preferredDefaultDevice?.deviceId ?? '');
- setSelectedDeviceName(preferredDefaultDevice?.name ?? preferredDefaultDevice?.deviceId ?? '');
- setDevicePickerOpen(false);
- }, [
- deviceOptions,
- initialWorkingDir,
- newSessionPreferences?.device?.deviceId,
+ useNewSessionWorkspacePreferences({
+ newSessionPreferences,
+ setNewSessionPreferences,
newSessionPreferencesLoaded,
- preferredDefaultDevice?.deviceId,
- preferredDefaultDevice?.name,
- routeDeviceExplicit,
+ setNewSessionPreferencesLoaded,
+ workingDirPreferenceOverridesRef,
+ initialWorkingDir,
+ userTouchedWorkspaceRef,
+ setDraft,
+ userTouchedDeviceRef,
routeDeviceId,
routeDeviceName,
- ]);
+ routeDeviceExplicit,
+ deviceOptions,
+ appliedDefaultDeviceKeyRef,
+ preferredDefaultDevice,
+ setSelectedDeviceId,
+ setSelectedDeviceName,
+ setDevicePickerOpen,
+ });
useNewSessionDefaultSelection({
newSessionPreferences,
@@ -1334,27 +1255,7 @@ export default function NewRemoteSessionScreen() {
// 无变化时返回原引用,不触发额外渲染。
useEffect(() => {
if (!deviceProviders.ready) return;
- setDraft((current) => {
- if (!current.providerId && !(current.agentKind === 'pi' && isCindyAutoModelId(current.model))) return current;
- const resolved = resolveRecentModelAndProvider(
- modelRows,
- { model: current.model, providerId: current.providerId },
- current.agentKind,
- true,
- deviceProviders.providers,
- deviceProviders.modelVisibilityOverrides,
- );
- const pairChanged = resolved.model !== current.model || resolved.providerId !== current.providerId;
- if (!pairChanged) return current;
- // 组合变化时同步校准 effort(codex review P2)、fastMode 保守置 false(可手动重开)。
- return {
- ...current,
- model: resolved.model,
- providerId: resolved.providerId,
- effort: reconcileEffortAfterFallback(modelRows, resolved, current.effort),
- ...(current.fastMode ? { fastMode: false } : {}),
- };
- });
+ setDraft((current) => reconcileNewSessionCatalogDraft(current, modelRows, deviceProviders));
}, [deviceProviders.ready, deviceProviders.providers, deviceProviders.modelVisibilityOverrides, modelRows]);
const draftContent = useMemo(
// pending(乐观上传中)也算数:拍完照立刻点创建是常见路径,create() 里会等它们落定。
@@ -1480,28 +1381,6 @@ export default function NewRemoteSessionScreen() {
useLayoutEffect(() => {
worktreeSettledRef.current = worktreeSettled;
}, [worktreeSettled]);
- const worktreeRowVisible = shouldShowWorktreeToggle({
- workspaceKind: draft.workspaceKind,
- workingDir: draft.workingDir,
- eligibility: worktreeEligibility,
- settled: worktreeSettled?.eligibility ?? null,
- enabled: worktreeEnabled,
- });
- const worktreePreferenceSaving =
- selectedDeviceId != null && (
- worktreePreferenceSavingDeviceId === selectedDeviceId
- || worktreePreferenceWriteTargetRef.current === selectedDeviceId
- );
- const worktreePreferenceAwaitingEcho =
- worktreePreferenceTransactionRef.current?.status === 'reconciling';
- const worktreePreferenceSyncKey = selectedDeviceId
- ? `${selectedDeviceId}\u0000${connectionEpoch}\u0000${presenceVersion}`
- : '';
- worktreePreferenceSyncKeyRef.current = worktreePreferenceSyncKey;
- const worktreePreferenceAuthorityUnknown = selectedDeviceId != null
- && worktreePreferenceAuthorityUnknownByDeviceRef.current.has(selectedDeviceId);
- const worktreeApplicable = draft.workspaceKind === 'project'
- && draft.workingDir.trim().length > 0;
// host preference 虽然持久化,连接代次仍属于权威读取 identity:桌面重启/重连后
// 即使 deviceId/repo 没变,也重新 GET,不能只相信手机内存里的旧快照。
const worktreeBranchPreferenceSyncKey = worktreeBranchPreferenceKey
@@ -1518,10 +1397,50 @@ export default function NewRemoteSessionScreen() {
worktreeBranchPreferenceSavingKey === worktreeBranchPreferenceKey
|| worktreeBranchPreferenceWriteTargetRef.current === worktreeBranchPreferenceKey
);
- const worktreeToggleDisabled =
- creating
- || worktreePreferenceSaving
- || (worktreeEligibility.status !== 'eligible' && !worktreeEnabled);
+ const {
+ worktreeEnabled,
+ worktreeApplicable,
+ worktreeToggleDisabled,
+ worktreeCreateBlocked,
+ worktreeCaptionKey,
+ worktreeControlCaptionKey,
+ resolveWorktreeCreateErrorKey,
+ isWorktreeCreateIntentCurrent,
+ toggleWorktree,
+ prepareWorktreeCreateIntent,
+ } = useNewSessionWorktreeSync({
+ selectedDeviceId,
+ connectionEpoch,
+ presenceVersion,
+ deviceLinkStatus,
+ deviceLinkStatusRef,
+ creating,
+ creatingRef,
+ draft,
+ maker,
+ openLink,
+ worktreeEligibility,
+ worktreeHostSupportsRecoveryKeyDiscard,
+ worktreeBranchPreferenceSaving,
+ worktreeBranchPreferenceReady,
+ worktreeBranchPreferenceReadyKeyRef,
+ worktreeBranchPreferenceError,
+ worktreeBranchPreferenceKey,
+ worktreeBranchPreferenceSyncKey,
+ worktreeBranchPreferenceSyncKeyRef,
+ worktreeBranchPreferenceWriteTargetRef,
+ worktreeBranchPreferenceTransactionRef,
+ worktreeBranchTargetRef,
+ worktreeEligibilityRef,
+ worktreeSourceBranchRef,
+ });
+ const worktreeRowVisible = shouldShowWorktreeToggle({
+ workspaceKind: draft.workspaceKind,
+ workingDir: draft.workingDir,
+ eligibility: worktreeEligibility,
+ settled: worktreeSettled?.eligibility ?? null,
+ enabled: worktreeEnabled,
+ });
// 分支区与 checkbox 是两条独立轴:OFF 时也可先选源分支;保存 checkbox 偏好在途
// 同样不影响只读的分支枚举。只有目标尚不具备 worktree 资格或创建在途时禁用。
const worktreeBranchDisabled = creating
@@ -1534,87 +1453,6 @@ export default function NewRemoteSessionScreen() {
// 2026-09-11: show this draft's explicit choice, otherwise the last host mirror.
// Eligibility failures still cannot silently downgrade an enabled worktree.
const worktreeChecked = worktreeEnabled;
- // caption 会多占一行、把上方选择器顶起,只在它解释「已勾选但创建被拦」时显示:
- // 探测中不显示;未勾选时创建不受资格影响,恢复中 / 探测失败也不显示。
- const worktreeCaptionKey = worktreeEnabled && worktreeEligibility.status !== 'probing'
- ? worktreeEligibilityCaptionKey(worktreeEligibility)
- : null;
- const worktreeCreateBlocked = shouldBlockNewSessionCreateForWorktree({
- applicable: worktreeApplicable,
- enabled: worktreeEnabled,
- eligibility: worktreeEligibility,
- // Saving a default does not change the explicit parameters of this request.
- preferenceSaving: false,
- })
- || (worktreeEnabled && (
- worktreeBranchPreferenceSaving
- || (worktreeEligibility.status === 'eligible' && !worktreeBranchPreferenceReady)
- || (worktreeBranchPreferenceTransactionRef.current?.key === worktreeBranchPreferenceKey
- && worktreeBranchPreferenceTransactionRef.current.status === 'unknown')
- ));
- const worktreeControlCaptionKey = worktreeCaptionKey
- ?? (worktreePreferenceAuthorityUnknown ? 'session.new.worktreeSettingsSyncFailed' : null)
- ?? (worktreeBranchPreferenceError ? 'session.new.worktreeBranchSyncFailed' : null);
- const resolveWorktreeCreateErrorKey = useCallback(() => (
- worktreeEligibilityCaptionKey(worktreeEligibilityRef.current)
- ?? (worktreeBranchPreferenceError
- ? 'session.new.worktreeBranchSyncFailed'
- : 'session.new.worktreeBranchSaving')
- ), [worktreeBranchPreferenceError]);
-
- useLayoutEffect(() => {
- worktreePreferenceRenderedRef.current = {
- deviceId: selectedDeviceId,
- enabled: worktreePreference.enabled,
- revision: worktreePreference.revision,
- };
- const transaction = worktreePreferenceTransactionRef.current;
- if (
- !transaction
- || (transaction.status !== 'reconciling' && transaction.status !== 'committed')
- || transaction.deviceId !== selectedDeviceId
- || worktreePreference.enabled !== transaction.enabled
- || worktreePreference.revision <= transaction.revisionAtStart
- ) return;
- worktreePreferenceTransactionRef.current = null;
- if (worktreePreferenceWriteTargetRef.current === transaction.deviceId) {
- worktreePreferenceWriteTargetRef.current = null;
- }
- setWorktreePreferenceSavingDeviceId(null);
- }, [selectedDeviceId, worktreePreference.enabled, worktreePreference.revision, worktreePreferenceAwaitingEcho]);
-
- useEffect(() => {
- if (!selectedDeviceId) return;
- const transaction = worktreePreferenceTransactionRef.current;
- if (
- transaction?.deviceId === selectedDeviceId
- && transaction.status === 'reconciling'
- && worktreePreference.revision > transaction.revisionAtStart
- && worktreePreference.enabled !== transaction.enabled
- ) {
- // The host echoed a different authoritative value. Do not silently use
- // it for this Create attempt: release the active spinner, retain the
- // user's requested value as an unknown obligation, and allow a retry.
- worktreePreferenceAuthorityUnknownByDeviceRef.current.set(selectedDeviceId, {
- enabled: transaction.enabled,
- revisionAtStart: transaction.revisionAtStart,
- });
- worktreePreferenceTransactionRef.current = null;
- if (worktreePreferenceWriteTargetRef.current === selectedDeviceId) {
- worktreePreferenceWriteTargetRef.current = null;
- }
- setWorktreePreferenceSavingDeviceId(null);
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- }
- const pending = worktreePreferenceAuthorityUnknownByDeviceRef.current.get(selectedDeviceId);
- if (
- !pending
- || worktreePreference.revision <= pending.revisionAtStart
- || worktreePreference.enabled !== pending.enabled
- ) return;
- worktreePreferenceAuthorityUnknownByDeviceRef.current.delete(selectedDeviceId);
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- }, [selectedDeviceId, worktreePreference.enabled, worktreePreference.revision, worktreePreferenceAwaitingEcho]);
const settleRenderedWorktreeBranchTransaction = useCallback((
key: string,
@@ -1655,65 +1493,6 @@ export default function NewRemoteSessionScreen() {
worktreeBranchPreferenceSyncKey,
worktreeSourceBranch,
]);
-
- const captureWorktreeCreateIntent = useCallback((): WorktreeCreateIntentSnapshot => {
- const target = { ...worktreeBranchTargetRef.current };
- const eligibility = worktreeEligibilityRef.current;
- const branchPreferenceKey = target.deviceId && eligibility.status === 'eligible'
- ? `${target.deviceId}\u0000${eligibility.baseRepo}`
- : '';
- return {
- applicable: target.deviceId.length > 0 && target.workingDir.trim().length > 0,
- enabled: worktreeEnabledRef.current,
- target,
- eligibility,
- sourceBranch: worktreeSourceBranchRef.current,
- branchPreferenceKey,
- branchPreferenceSyncKey: worktreeBranchPreferenceSyncKeyRef.current,
- };
- }, []);
-
- const isWorktreeCreateIntentCurrent = useCallback((
- intent: WorktreeCreateIntentSnapshot,
- ): boolean => {
- if (!intent.applicable) return true;
- const currentTarget = worktreeBranchTargetRef.current;
- if (
- deviceLinkStatusRef.current !== 'online'
- || currentTarget.deviceId !== intent.target.deviceId
- || currentTarget.workingDir.trim() !== intent.target.workingDir.trim()
- ) return false;
- // ineligible 目标不创建 worktree,无需等偏好同步/就绪——提前返回,
- // 避免偏好 GET 在途时被下方偏好守卫拦截;与 enabled 无关(2026-08-07 裁决)。
- // 但快照不能替代实时状态:await 期间同目标可能被重探回 probing/eligible/
- // detect-failed,旧 ineligible 快照必须复核 live ref 仍为 ineligible 才放行,
- // 否则回到 fail closed(探测未定不等于确认不合格)。
- if (!intent.enabled) return true;
- if (intent.eligibility.status === 'ineligible') {
- return worktreeEligibilityRef.current.status === 'ineligible';
- }
- // The click captures the displayed choice. Background defaults and persistence
- // ACKs cannot invalidate an already submitted request.
- // ineligible 已在前面提前返回,此处只可能是 eligible(2026-08-07 裁决)。
- if (intent.eligibility.status !== 'eligible') return false;
- // 与 ineligible 快照同理:eligible 快照也必须复核 live 资格仍是同一 repo 的
- // eligible,await 期间被重探成别的状态或换了 repo 都不能继续建 worktree。
- const currentEligibility = worktreeEligibilityRef.current;
- if (
- currentEligibility.status !== 'eligible'
- || currentEligibility.baseRepo !== intent.eligibility.baseRepo
- ) return false;
- const branchTransaction = worktreeBranchPreferenceTransactionRef.current;
- // A missing branch snapshot may only be a pending read, not host consent
- // to use the detected branch. Checkbox defaults remain independent.
- return worktreeBranchPreferenceReadyKeyRef.current === intent.branchPreferenceSyncKey
- && worktreeBranchPreferenceSyncKeyRef.current === intent.branchPreferenceSyncKey
- && worktreeBranchPreferenceWriteTargetRef.current !== intent.branchPreferenceKey
- && !(
- branchTransaction?.key === intent.branchPreferenceKey
- && (branchTransaction.status === 'writing' || branchTransaction.status === 'unknown')
- );
- }, []);
const createValidation = useMemo(
() => runtimePending ? t('session.new.modelLoading') : validateNewSessionDraft(draft, draftContent),
[draft, draftContent, runtimePending, t],
@@ -1879,22 +1658,29 @@ export default function NewRemoteSessionScreen() {
);
const patchDraft = useCallback((patch: Partial<NewSessionDraft>) => {
- if (patch.firstMessage !== undefined) {
- firstMessageRef.current = patch.firstMessage;
- if (!creatingRef.current) editRecoveredDraft({ firstMessage: patch.firstMessage });
- voiceDictionaryLearningTrackerRef.current?.inspectDraft(patch.firstMessage);
- }
- setDraft((current) => ({ ...current, ...patch }));
+ patchNewSessionDraft(
+ {
+ firstMessageRef,
+ creatingRef,
+ editRecoveredDraft,
+ voiceDictionaryLearningTrackerRef,
+ setDraft,
+ },
+ patch,
+ );
}, [editRecoveredDraft]);
const openPluginPalette = useCallback(() => {
- const next = composerDocumentProjectedText(appendComposerPluginTrigger(textComposerDocument(firstMessageRef.current)));
- patchDraft({ firstMessage: next });
- const selection = { start: next.length, end: next.length };
- firstMessageSelectionRef.current = selection;
- setFirstMessageSelection(selection);
- if (composerPillOpen.onCollapsedPress) composerPillOpen.onCollapsedPress();
- else requestAnimationFrame(() => firstMessageInputRef.current?.focus());
+ openNewSessionPluginPalette({
+ firstMessageRef,
+ patchDraft,
+ firstMessageSelectionRef,
+ setFirstMessageSelection,
+ focusComposer: () => {
+ if (composerPillOpen.onCollapsedPress) composerPillOpen.onCollapsedPress();
+ else requestAnimationFrame(() => firstMessageInputRef.current?.focus());
+ },
+ });
}, [composerPillOpen.onCollapsedPress, patchDraft]);
const selectComposerPlugin = useCallback((plugin: ComposerPlugin, roster: ComposerPlugin[]) => {
@@ -1911,16 +1697,22 @@ export default function NewRemoteSessionScreen() {
}, [patchDraft]);
const setFirstMessageDraft = useCallback((next: SetStateAction<string>) => {
- const value = typeof next === 'function' ? next(firstMessageRef.current) : next;
- firstMessageRef.current = value;
- if (!creatingRef.current) editRecoveredDraft({ firstMessage: value });
- setDraft((current) => ({ ...current, firstMessage: value }));
- voiceDictionaryLearningTrackerRef.current?.inspectDraft(value);
+ setNewSessionFirstMessage(
+ {
+ firstMessageRef,
+ creatingRef,
+ editRecoveredDraft,
+ voiceDictionaryLearningTrackerRef,
+ setDraft,
+ },
+ next,
+ );
}, [editRecoveredDraft]);
useIncomingShareComposer({
destination: 'new', ready: isShareTargetFocused && newSessionPreferencesLoaded && !creating,
- appendText: text => setFirstMessageDraft(current => [current, text].filter(Boolean).join('\n\n')),
+ appendText: text => appendNewSessionSharedText({ firstMessageRef, creatingRef, editRecoveredDraft,
+ voiceDictionaryLearningTrackerRef, setDraft }, text),
attachmentCount: attachments.length,
enqueueUploads, getPendingUploadCount, onError: setAttachmentError,
});
@@ -2007,7 +1799,7 @@ export default function NewRemoteSessionScreen() {
}
// A share can arrive before the first computer is selected. Its uploads
// are not tied to a previous host; only a real host switch invalidates them.
- const changesExistingDevice = !!selectedDeviceIdRef.current && option.deviceId !== selectedDeviceIdRef.current;
+ const previousDeviceId = selectedDeviceIdRef.current;
selectedDeviceIdRef.current = option.deviceId;
setSelectedDeviceId(option.deviceId);
setSelectedDeviceName(option.name || option.deviceId);
@@ -2029,21 +1821,12 @@ export default function NewRemoteSessionScreen() {
setBrowseLoading(false);
setBrowseError(null);
setContextSheetOpen(false);
- if (changesExistingDevice) {
- // 切换电脑丢弃草稿附件前 best-effort 回收已上传的中转对象(codex review #504)。
- for (const attachment of attachments) {
- discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });
- }
- // 在途上传同样作废(codex review R10):不取消的话它们完成后会经 onUploaded 把
- // 上一台电脑期间选的附件塞进新电脑的草稿;丢弃后由控制器在完成时回收 OSS 对象。
- discardAllPendingUploads();
- releaseUploadedSources(attachments.map((attachment) => attachment.id));
- setAttachments([]);
- setMediaAssetAttachments({});
- setAttachmentPreviews({});
- composerAnnotationsRef.current?.forgetAllAttachments();
- setAttachmentError(null);
- }
+ clearNewSessionAttachmentsForDeviceChange({
+ previousDeviceId, nextDeviceId: option.deviceId, attachments,
+ getToken: () => auth.getAccessToken(), discardAllPendingUploads, releaseUploadedSources,
+ setAttachments, setMediaAssetAttachments, setAttachmentPreviews, setAttachmentError,
+ forgetAllAnnotations: () => composerAnnotationsRef.current?.forgetAllAttachments(),
+ });
initialWorkspaceKeyRef.current = null;
setDraft((current) => ({
...current,
@@ -2152,56 +1935,13 @@ export default function NewRemoteSessionScreen() {
// 否则 UI 的 rowFastEditable 已显示关、创建仍发 fastMode:true 被拒。仅能力表
// 与目录均就绪时判定(缓存缺失/加载中不动作,避免切设备瞬间误关)。
useEffect(() => {
- if (!selectedDeviceId) return;
- // 来源 id 与 changeSelectedFastMode 同口径:显式选了来源用 providerId,默认路由
- // (null)草稿可用推断来源(activeSourceIdRef)开启 Fast——撤销检查不得漏掉它
- // (codex review P2:目录 revision 改变默认来源/移除 Fast 支持时,null-provider
- // 草稿仍在发 fastMode:true)。
- const pid = draft.providerId ?? activeSourceIdRef.current;
- if (!pid) return;
- const capsKnown = getCachedAgentCapabilities(buildAgentCapabilitiesCacheKey(selectedDeviceId, draft.agentKind)) !== undefined;
- if (draft.fastMode) {
- if (
- capsKnown
- && catalogReadyRef.current
- && !isFastRestorable(
- draft.agentKind,
- pid,
- draft.model,
- modelRowsRef.current,
- targetAgentHasFast(selectedDeviceId, draft.agentKind),
- draft.fastMode,
- )
- ) {
- setDraft((current) => (
- current.fastMode
- && current.agentKind === draft.agentKind
- && current.model === draft.model
- && current.providerId === draft.providerId
- ? { ...current, fastMode: false }
- : current
- ));
- }
- return;
- }
- const rememberedFast = draftMemory.getFast(draft.agentKind, pid, draft.model) ?? false;
- if (!rememberedFast) return;
- if (!isFastRestorable(
- draft.agentKind,
- pid,
- draft.model,
- modelRowsRef.current,
- targetAgentHasFast(selectedDeviceId, draft.agentKind),
- rememberedFast,
- )) return;
- setDraft((current) => (
- !current.fastMode
- && current.agentKind === draft.agentKind
- && current.model === draft.model
- && current.providerId === draft.providerId
- ? { ...current, fastMode: rememberedFast }
- : current
- ));
+ restoreNewSessionFastPreference({
+ selectedDeviceId, draft, activeSourceId: activeSourceIdRef.current,
+ capabilitiesKnown: getCachedAgentCapabilities(buildAgentCapabilitiesCacheKey(selectedDeviceId, draft.agentKind)) !== undefined,
+ catalogReady: catalogReadyRef.current, modelRows: modelRowsRef.current,
+ hasFast: () => targetAgentHasFast(selectedDeviceId, draft.agentKind),
+ draftMemory, setDraft,
+ });
// capabilities / modelRows / deviceProviders.ready 是触发信号(能力表或目录变化
// 都重评);目标归属由 targetAgentHasFast 的 (设备, agent) 键控缓存校验,不靠
// state 身份判断。判定体内经 catalogReadyRef 读最新就绪态。
@@ -2519,66 +2259,28 @@ export default function NewRemoteSessionScreen() {
}
}, [selectedDeviceId, maker, openLink]);
- const selectWorkingDir = useCallback((workingDir: string) => {
- patchDraft({ workingDir });
- setBrowseOpen(false);
- setBrowseError(null);
- 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' });
- patchDraft({ workspaceKind: 'dialogue', workingDir: '' });
- setWorkspacePickerOpen(false);
- setBrowseOpen(false);
- setShowHiddenDirectories(false);
- }, [patchDraft]);
-
- const selectRecentProject = useCallback((workingDir: string) => {
- userTouchedWorkspaceRef.current = true;
- // 显式点选最近项目 = 该设备的目录记忆(#4103);设备未定时只记模式。
- const remembered = rememberWorkingDirForDevice(workingDir);
- void saveNewSessionPreferences({
- workspaceKind: 'project',
- ...(remembered ? { workingDirForDevice: remembered } : {}),
- });
- patchDraft({ workspaceKind: 'project', workingDir });
- setWorkspacePickerOpen(false);
- setBrowseOpen(false);
- setShowHiddenDirectories(false);
- }, [patchDraft, rememberWorkingDirForDevice]);
-
- const openProjectBrowse = useCallback(() => {
- userTouchedWorkspaceRef.current = true;
- void saveNewSessionPreferences({ workspaceKind: 'project' });
- patchDraft({ workspaceKind: 'project' });
- setWorkspacePickerOpen(false);
- setBrowseOpen(true);
- // 用户显式选择浏览时,消费初始工作区决策,避免 auto-select effect 关掉浏览改选最近项目。
- initialWorkspaceKeyRef.current = `${selectedDeviceId}:${initialWorkingDir ?? ''}`;
- void loadBrowsePath(draft.workingDir.trim() || '~');
- }, [draft.workingDir, loadBrowsePath, patchDraft, selectedDeviceId, initialWorkingDir]);
+ const {
+ selectWorkingDir,
+ rememberWorkingDirForDevice,
+ chooseWorkingDir,
+ selectDialogueWorkspace,
+ selectRecentProject,
+ openProjectBrowse,
+ } = useNewSessionWorkspaceActions({
+ draft,
+ selectedDeviceId,
+ initialWorkingDir,
+ patchDraft,
+ setBrowseOpen,
+ setBrowseError,
+ setShowHiddenDirectories,
+ workingDirPreferenceOverridesRef,
+ setNewSessionPreferences,
+ userTouchedWorkspaceRef,
+ setWorkspacePickerOpen,
+ initialWorkspaceKeyRef,
+ loadBrowsePath,
+ });
// 选回被控电脑自己的模型:不再在下次打开时恢复这个 agent 选过的其他电脑 / 分享来的模型。
const forgetRemoteAgentPick = useCallback((agentKind: NewSessionAgentKind) => {
@@ -3244,242 +2946,6 @@ export default function NewRemoteSessionScreen() {
worktreeEligibility,
]);
- // —— worktree 勾选播种:选中设备后读工作端 get-new-maker-defaults 的 worktreeEnabled
- // (vendor 无关,agentKind 只是通道入参,经 ref 读当前值,不因切 agent 重播)。
- // 设备切换 / 链路重连重新播种;老被控端 / 缺字段 / 拉取失败只保留当前镜像。
- // 全新设备在 store 中没有镜像时本来就是默认未勾选,无需失败路径代替宿主写值。
- const worktreeSeedAgentKindRef = useRef(draft.agentKind);
- worktreeSeedAgentKindRef.current = draft.agentKind;
- // Read the host capability through a ref: probing a different directory must
- // not cancel a device-wide defaults request. Old hosts need no missing-field retry.
- const worktreeHostSupportsRecoveryKeyDiscardRef = useRef(worktreeHostSupportsRecoveryKeyDiscard);
- worktreeHostSupportsRecoveryKeyDiscardRef.current = worktreeHostSupportsRecoveryKeyDiscard;
- useEffect(() => {
- const seq = ++worktreeSeedSeqRef.current;
- const syncKey = worktreePreferenceSyncKey;
- if (!selectedDeviceId || !syncKey || deviceLinkStatus !== 'online') return undefined;
- const preferenceRevisionAtStart =
- remoteSessionStore.getNewMakerWorktreePreference(selectedDeviceId).revision;
- let cancelled = false;
- let retryTimer: ReturnType<typeof setTimeout> | null = null;
- const scheduleRetry = () => {
- if (retryTimer) return;
- retryTimer = setTimeout(() => {
- if (!cancelled) setWorktreeSeedRetryNonce((value) => value + 1);
- }, 1_500);
- };
- // 与上面 detect effect 同款:先建链再拉,包瞬态重试——app 后台恢复时 relay 常在
- // 重连窗口,裸调会抛 NOT_CONNECTED 并把工作端持久化的勾选偏好静默播种成未勾。
- void withTransientRemoteRetry(async () => {
- await openLink(selectedDeviceId);
- return maker.getNewMakerDefaults(worktreeSeedAgentKindRef.current);
- }, { maxAttempts: 2 })
- .then((defaults) => {
- if (
- cancelled
- || seq !== worktreeSeedSeqRef.current
- || worktreePreferenceSyncKeyRef.current !== syncKey
- ) return;
- // 请求发出后若已收到更晚的 push / 用户点击,旧 pull 不再有覆盖权。
- if (
- remoteSessionStore.getNewMakerWorktreePreference(selectedDeviceId).revision
- !== preferenceRevisionAtStart
- ) return;
- const classification = classifyWorktreePreferenceSeed(defaults);
- if (classification.status === 'ready') {
- // Update only the host mirror. Explicit draft choices remain separate.
- remoteSessionStore.setNewMakerWorktreePreference(
- selectedDeviceId,
- classification.enabled,
- );
- return;
- }
- if (
- classification.status === 'missing'
- && worktreeHostSupportsRecoveryKeyDiscardRef.current === false
- ) {
- // Old hosts cannot persist this preference and also lack the recovery
- // capability marker. A new host can transiently return `{}` before its
- // renderer cache arrives; keep the last mirror and retry in that case.
- return;
- }
- scheduleRetry();
- })
- .catch((error: unknown) => {
- if (
- cancelled
- || seq !== worktreeSeedSeqRef.current
- || worktreePreferenceSyncKeyRef.current !== syncKey
- ) return;
- if (isWorktreeChannelNotAllowedError(error)) {
- return;
- }
- // A failed defaults read leaves the displayed value usable for creation.
- scheduleRetry();
- });
- return () => {
- cancelled = true;
- if (retryTimer) clearTimeout(retryTimer);
- };
- }, [
- connectionEpoch,
- deviceLinkStatus,
- presenceVersion,
- selectedDeviceId,
- worktreePreferenceSyncKey,
- worktreeSeedRetryNonce,
- maker,
- openLink,
- ]);
-
- // Saving the next default is independent of using this draft's explicit choice.
- // An accepted write may never echo back; release the control after 10 seconds.
- useEffect(() => {
- if (!worktreePreferenceSavingDeviceId || !worktreePreferenceAwaitingEcho) return;
- const transaction = worktreePreferenceTransactionRef.current;
- const timer = setTimeout(() => {
- if (!transaction || worktreePreferenceTransactionRef.current !== transaction) return;
- worktreePreferenceAuthorityUnknownByDeviceRef.current.set(transaction.deviceId, {
- enabled: transaction.enabled,
- revisionAtStart: transaction.revisionAtStart,
- });
- worktreePreferenceTransactionRef.current = null;
- worktreePreferenceWriteTargetRef.current = null;
- setWorktreePreferenceSavingDeviceId(null);
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- }, 10_000);
- return () => clearTimeout(timer);
- }, [worktreePreferenceSavingDeviceId, worktreePreferenceAwaitingEcho]);
-
- // 用户显式点击开关:先写工作端,工作端接受后才更新手机内存镜像。
- // 资格不满足导致的禁用不会走到这里 —— 环境因素不抹掉用户偏好;
- // 写入失败也不在手机上制造一份假的持久状态。
- const toggleWorktree = useCallback(() => {
- if (
- creatingRef.current
- || !selectedDeviceId
- || worktreePreferenceSaving
- || worktreePreferenceWriteTargetRef.current === selectedDeviceId
- ) return;
- const targetDeviceId = selectedDeviceId;
- const next = !worktreeEnabledRef.current;
- worktreeChoicesRef.current.set(targetDeviceId, next);
- worktreeEnabledRef.current = next;
- setWorktreeChoiceVersion((value) => value + 1);
- // 播种在途回包不得覆盖用户显式选择(seq 作废旧回包)。
- worktreeSeedSeqRef.current += 1;
- const preferenceRevisionAtStart =
- remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId).revision;
- const writeSeq = worktreePreferenceWriteSeqRef.current + 1;
- worktreePreferenceWriteSeqRef.current = writeSeq;
- if (worktreePreferenceAuthorityUnknownByDeviceRef.current.delete(targetDeviceId)) {
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- }
- const transaction: WorktreePreferenceWriteTransaction = {
- seq: writeSeq,
- deviceId: targetDeviceId,
- enabled: next,
- revisionAtStart: preferenceRevisionAtStart,
- status: 'writing',
- };
- // Switching devices may replace a write that is still awaiting ACK/echo.
- // Preserve its uncertainty in the existing per-device reconciliation map.
- const previousTransaction = worktreePreferenceTransactionRef.current;
- if (previousTransaction && previousTransaction.deviceId !== targetDeviceId) {
- worktreePreferenceAuthorityUnknownByDeviceRef.current.set(previousTransaction.deviceId, {
- enabled: previousTransaction.enabled,
- revisionAtStart: previousTransaction.revisionAtStart,
- });
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- }
- worktreePreferenceTransactionRef.current = transaction;
- // Serialize preference writes; Create/Goal use the synchronous draft choice above.
- worktreePreferenceWriteTargetRef.current = targetDeviceId;
- setWorktreePreferenceSavingDeviceId(targetDeviceId);
- const releaseWrite = () => {
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- if (worktreePreferenceTransactionRef.current?.seq === writeSeq) {
- worktreePreferenceTransactionRef.current = null;
- }
- if (worktreePreferenceWriteTargetRef.current === targetDeviceId) {
- worktreePreferenceWriteTargetRef.current = null;
- }
- setWorktreePreferenceSavingDeviceId(null);
- };
- const markAuthorityUnknown = () => {
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- worktreePreferenceAuthorityUnknownByDeviceRef.current.set(targetDeviceId, {
- enabled: next,
- revisionAtStart: preferenceRevisionAtStart,
- });
- setWorktreePreferenceAuthorityVersion((value) => value + 1);
- releaseWrite();
- setWorktreeSeedRetryNonce((value) => value + 1);
- };
- const armCommittedRender = () => {
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- transaction.status = 'committed';
- const rendered = worktreePreferenceRenderedRef.current;
- if (
- rendered.deviceId === targetDeviceId
- && rendered.enabled === next
- && rendered.revision > preferenceRevisionAtStart
- ) releaseWrite();
- };
- void (async () => {
- try {
- const outcome = await applyWorktreePreferenceOnHost({
- enabled: next,
- apply: maker.applyNewMakerWorktreePref,
- // unsupported 可能是“有偏好写穿、缺安全 worktree 能力”,也可能是最老端
- // 连偏好 channel 都没有:先写 host;只有后者且用户明确点 OFF 时才清手机
- // 保留的旧 ON 镜像。断连/超时不降级,仍保留 ON + fail closed。
- allowUnsupportedDisableFallback:
- !next && worktreeEligibility.status === 'unsupported',
- mirror: (enabled) => {
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- const current = remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId);
- if (current.revision === preferenceRevisionAtStart) {
- remoteSessionStore.setNewMakerWorktreePreference(targetDeviceId, enabled);
- }
- const accepted = remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId);
- if (
- accepted.revision > preferenceRevisionAtStart
- && accepted.enabled === enabled
- ) {
- armCommittedRender();
- } else {
- markAuthorityUnknown();
- }
- },
- });
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- if (outcome === 'accepted') {
- // Main acknowledged the broadcast; track persistence separately from creation.
- transaction.status = 'reconciling';
- setWorktreeSeedRetryNonce((value) => value + 1);
- }
- } catch (error) {
- if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
- if (isWorktreeChannelNotAllowedError(error)) {
- // Explicit old-channel rejection proves this ON request did not
- // commit. Keep the rendered value and let the user continue.
- releaseWrite();
- return;
- }
- // Lost ACK / disconnect may have committed remotely. Reconcile the default
- // via push/GET, while the explicit draft choice remains usable.
- markAuthorityUnknown();
- }
- })();
- }, [
- maker,
- selectedDeviceId,
- worktreeEnabled,
- worktreePreferenceSaving,
- worktreeEligibility.status,
- ]);
-
useEffect(() => {
const tracker = createMobileVoiceDictionaryLearningTracker({
submit: (request) => maker.recordVoiceDictionaryLearning(request),
@@ -3493,6 +2959,18 @@ export default function NewRemoteSessionScreen() {
};
}, [maker]);
+ const voiceSelectionInput = {
+ voiceSelectionUserOwnedRef,
+ voiceRecordingActiveRef,
+ voiceStopInFlightRef,
+ voiceStopGestureSelectionGuardRef,
+ voicePendingSelectionEchoesRef,
+ firstMessageRef,
+ firstMessageSelectionRef,
+ setFirstMessageSelection,
+ setFirstMessageDraft,
+ };
+
const startVoiceRecording = useCallback(async () => {
if (
voicePermissionRequestInFlightRef.current
@@ -3635,30 +3113,7 @@ export default function NewRemoteSessionScreen() {
},
localVoiceInputHistory: () => localVoiceInputHistory,
readCurrentDraft: () => firstMessageRef.current,
- onDraftChanged: (text, selection, replacement) => {
- // Follow ASR until a native edit claims the caret; then preserve its
- // position in the surrounding text as the voice range changes length.
- let nextSelection = voiceSelectionUserOwnedRef.current ? undefined : selection;
- if (voiceSelectionUserOwnedRef.current && replacement) {
- const replacementEnd = replacement.start + replacement.text.length;
- const rebaseOffset = (offset: number) => {
- if (offset <= replacement.start) return offset;
- if (offset >= replacement.end) return offset + replacementEnd - replacement.end;
- return Math.min(offset, replacementEnd);
- };
- const current = firstMessageSelectionRef.current;
- nextSelection = { start: rebaseOffset(current.start), end: rebaseOffset(current.end) };
- }
- if (nextSelection) {
- const previous = firstMessageSelectionRef.current;
- if (nextSelection.start !== previous.start || nextSelection.end !== previous.end) {
- voicePendingSelectionEchoesRef.current.push(nextSelection);
- }
- firstMessageSelectionRef.current = nextSelection;
- setFirstMessageSelection(nextSelection);
- }
- setFirstMessageDraft(text);
- },
+ onDraftChanged: (text, selection, replacement) => publishNewSessionVoiceDraft(voiceSelectionInput, text, selection, replacement),
onStateChanged: (next) => {
// 旧 controller 的取消可晚于新启动完成,只允许本次启动交接 UI 状态。
if (voiceStartupSeqRef.current !== startupSeq) return;
@@ -3734,33 +3189,7 @@ export default function NewRemoteSessionScreen() {
}, [openLink, selectedDeviceId, setFirstMessageDraft, voiceIsProcessing, voiceState]);
const finishVoiceRecording = useCallback(async (): Promise<string | null> => {
- if (voiceStopInFlightRef.current) return null;
- const controller = voiceControllerSessionRef.current;
- if (!controller) return null;
- if (!voiceRecordingActiveRef.current && voiceState !== 'listening') return null;
- voiceStartupSeqRef.current += 1;
- voiceStartupInFlightRef.current = false;
- voiceStopInFlightRef.current = true;
- voiceControllerSessionRef.current = null;
- voiceRecordingActiveRef.current = false;
- setVoiceState('submitting');
- setVoiceError(null);
- try {
- const latestDraft = await controller.stop();
- setVoiceState('done');
- requestAnimationFrame(() => {
- firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });
- });
- return latestDraft;
- } catch (err) {
- voiceControllerSessionRef.current = null;
- voiceRecordingActiveRef.current = false;
- setVoiceState('error');
- setVoiceError(formatRemoteError(err));
- return null;
- } finally {
- voiceStopInFlightRef.current = false;
- }
+ return finishNewSessionVoiceRecording({ voiceStopInFlightRef, voiceControllerSessionRef, voiceRecordingActiveRef, voiceState, voiceStartupSeqRef, voiceStartupInFlightRef, firstMessageSelectionRef, firstMessageInputRef, setVoiceState, setVoiceError, requestAnimationFrame, formatRemoteError });
}, [voiceState]);
const openVoiceSettings = useCallback(() => {
@@ -4186,41 +3615,20 @@ export default function NewRemoteSessionScreen() {
if (fallback && fallback.kind !== draft.agentKind) switchAgent(fallback.kind);
}, [availableAgentKinds, draft.agentKind, switchAgent]);
- 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;
- initialWorkspaceKeyRef.current = key;
-
- // 先用该设备记住的上次显式选择(#4103),没有再取最近项目首项。
- const initialWorkspace = pickInitialNewSessionWorkspace(
- draft.workingDir,
- recentWorkspaces,
- newSessionPreferences?.workingDirByDevice?.[selectedDeviceId] ?? null,
- );
- if (initialWorkspace) {
- selectWorkingDir(initialWorkspace);
- return;
- }
-
- setBrowseOpen(true);
- void loadBrowsePath('~');
- }, [
+ useNewSessionInitialWorkspace({
selectedDeviceId,
- draft.workspaceKind,
- draft.workingDir,
+ draft,
+ newSessionPreferencesLoaded,
+ userTouchedDeviceRef,
+ preferredDefaultDevice,
initialWorkingDir,
- loadBrowsePath,
+ initialWorkspaceKeyRef,
recentWorkspaces,
+ newSessionPreferences,
selectWorkingDir,
- newSessionPreferencesLoaded,
- newSessionPreferences?.workingDirByDevice,
- preferredDefaultDevice?.deviceId,
- ]);
+ setBrowseOpen,
+ loadBrowsePath,
+ });
const selectSlashCommand = useCallback((command: MobileSlashCommand) => {
const current = firstMessageRef.current;
@@ -4497,11 +3905,8 @@ export default function NewRemoteSessionScreen() {
setModelSheetOpen(true);
return;
}
- const worktreeIntent = captureWorktreeCreateIntent();
- if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
- setError(t(resolveWorktreeCreateErrorKey()));
- return;
- }
+ const worktreeIntent = prepareWorktreeCreateIntent(key => setError(t(key)));
+ if (!worktreeIntent) return;
creatingRef.current = true;
const startedAt = Date.now();
setCreateStartedAt(startedAt);
@@ -4514,14 +3919,10 @@ export default function NewRemoteSessionScreen() {
// 建出重复会话(codex review P2)。交接成功后锁保持到组件销毁;「返回编辑」
// 回来的是新 mount,creatingRef 天然复位。
let handedOff = false;
- let releasePrecreatedRegistration: (() => void) | null = null;
- let releaseDurableCreation: (() => void) | null = null;
+ const creationLeases: { precreated: (() => void) | null; durable: (() => void) | null } = { precreated: null, durable: null };
const accountIdAtCreate = auth.user?.id?.trim() ?? '';
const authOwnerAtCreate = getMobileAuthOwner();
- const isCurrentOwner = () => (
- authOwnerAtCreate.accountId === accountIdAtCreate
- && isMobileAuthOwnerCurrent(authOwnerAtCreate)
- );
+ const { isCurrentOwner, worktreeAccountId } = captureNewSessionOwner(authOwnerAtCreate, accountIdAtCreate);
try {
if (!isCurrentOwner()) return;
// 选了另一台电脑的模型:模型 / 来源 / 档位与 Agent 所在电脑一起落进要创建的草稿。
@@ -4573,7 +3974,6 @@ export default function NewRemoteSessionScreen() {
name: selectedDeviceName || selectedDeviceId,
},
});
- const worktreeAccountId = authOwnerAtCreate.accountId;
const creatingWorktree = worktreeIntent.applicable
&& worktreeIntent.enabled
&& worktreeIntent.eligibility.status === 'eligible';
@@ -4633,254 +4033,42 @@ export default function NewRemoteSessionScreen() {
// / 首条消息 enqueue 全部由 newSessionCreation 模块级后台管线完成(本页
// unmount 不终止),失败重试面在会话页(横幅:重试 / 返回编辑)。
// Recovery may have cancelled this creation while the editor was already open.
- const previousRecovery = outboxRecoveryRef.current;
- const recovering = previousRecovery
- ? getCurrentMobileOutboxRecords().find((r) => r.deviceId === previousRecovery.deviceId
- && r.item.clientId === previousRecovery.item.clientId
- && r.item.sessionId === previousRecovery.item.sessionId)
- : null;
- if (previousRecovery && !recovering) throw new Error('OUTBOX_STALE_WRITE');
- if (recovering && recovering.deviceId !== selectedDeviceId) {
- throw new Error(t('session.outbox.recoveryTarget'));
- }
- if (recovering?.creation?.cancelled && previousRecovery?.creation
- && effectiveDraft.workingDir === previousRecovery.creation.draft.workingDir
- && effectiveDraft.workingDir !== recovering.creation.draft.workingDir) {
- // Eligibility and branch preference belong to the old directory. Let the
- // form probe the restored target before accepting another submission.
- outboxRecoveryRef.current = recovering;
- setDraft((current) => ({ ...current, workingDir: recovering.creation!.draft.workingDir }));
- return;
- }
- const recoveryIdentity = recovering ? outboxCreationRetryIdentity(recovering, createNewSessionId) : null;
- const sessionId = recoveryIdentity?.sessionId ?? createNewSessionId();
- if (recovering) {
- // Editing creation parameters is allowed only after the original task is proven absent.
- let found = false;
- try { found = !!(await maker.getSession(recovering.item.sessionId)); }
- catch (error) {
- if (!formatRemoteError(error).includes('NOT_FOUND')) throw error;
- }
- if (!isCurrentOwner()) return;
- if (found) {
- const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === recovering.item.clientId && r.item.sessionId === recovering.item.sessionId);
- if (latest && !latest.prepared) await mobileDurableOutbox.update(latest, { suspended: false, state: 'queued' });
- throw new Error(t('session.outbox.taskAlreadyCreated'));
- }
- }
- // Preserve input and attachment bytes before reserving or creating a remote worktree.
- const agentKindSnapshot = effectiveDraft.agentKind;
- const deviceIdSnapshot = selectedDeviceId;
- // 老协议 plan 一次性语义(对齐桌面 PR#494):入队后恢复进入前的底层权限档。
- const legacyPlanRestore = effectiveDraft.permissionMode === 'plan'
- ? (() => {
- const fallback = runtimeOptions.permissionOptions.find((option) => option.id !== 'plan')?.id ?? 'ask';
- const remembered = prePlanPermissionModeRef.current;
- return remembered && remembered !== 'plan' ? remembered : fallback;
- })()
- : null;
- if (!isCurrentOwner()) return;
- releaseDurableCreation = holdNewSessionCreationDraft(sessionId);
- const firstMessageClientId = recovering?.item.clientId ?? createOutboxClientId();
- // Legacy Plan requires a live session-wide permission change. Keep its existing
- // online creation pipeline instead of introducing deferred permission mutations.
- const useDurableCreation = legacyPlanRestore === null;
- if (recovering && !useDurableCreation) throw new Error(t('session.outbox.legacyPlanRecovery'));
- if (useDurableCreation) {
- const firstRecord: DurableOutboxRecord = {
- version: 1, accountId: authOwnerAtCreate.accountKey, deviceId: deviceIdSnapshot,
- ...(recoveryIdentity ? { storageSessionId: recoveryIdentity.storageSessionId } : {}),
- createdAt: recovering?.createdAt ?? Date.now(), state: recovering ? 'failed' : 'queued',
- suspended: !!recovering || creatingWorktree, uploads: [], clearBoundaryMs: null,
- creation: { draft: effectiveDraft, deviceName: selectedDeviceName,
- // Replacing a restored draft does not hand it to the background pipeline.
- // Keep its recovery intent durable until the creation pipeline takes over.
- ...(recovering ? { editReady: true } : {}),
- ...(creatingWorktree ? { originalWorkingDir: effectiveDraft.workingDir } : {}),
- planModeArm: planModeCapability && planModeDraftOn, restorePermissionMode: legacyPlanRestore },
- item: buildOutboxItem({
- clientId: firstMessageClientId, sessionId, text: effectiveDraft.firstMessage,
- quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],
- permissionModeAtSend: effectiveDraft.permissionMode, readyAttachments: sendAttachments,
- readyPreviews: sendAttachments.map((a) => attachmentPreviews[a.id] ?? null), claimedUploads: [],
- }),
- };
- const saved = await persistNewSessionCreationDraft({
- record: firstRecord, recovering, getUploadedSource,
- isCurrent: () => isCurrentOwner() && ensureDeviceAlive(),
- });
- if (!saved) return;
- outboxRecoveryRef.current = saved;
- if (!isCurrentOwner() || !ensureDeviceAlive()) return;
- releaseUploadedSources(sendAttachments.map((a) => a.id));
- }
- let precreatedWorktree: {
- path: string;
- recoveryKey: string;
- originalWorkingDir: string;
- createdAt?: number;
- } | undefined;
- // ㉙ 设备切换中止助手(独立 review P1-2/P1-3):检测到设备已切换 → 已产生远端
- // 副作用(precreated)走 compensatePrecreatedWorktree——**先 discardPrecreated
- // 获严格 ACK 才 forget**(forget 删唯一账本,未 discard 就删 = 永久孤儿),
- // ACK 失败/未知保留 ledger 交 recovery;返回 true 供调用方 return。
- const abortIfDeviceSwitched = async (): Promise<boolean> => {
- if (ensureDeviceAlive()) return false;
- if (precreatedWorktree) {
- const pwt = precreatedWorktree;
- await compensatePrecreatedWorktree({
- sessionId,
- recoveryKey: pwt.recoveryKey,
- createdAt: pwt.createdAt ?? Date.now(),
- phase: 'precreated',
- discard: () => maker.worktree.discardPrecreated({
- sessionId,
- recoveryKey: pwt.recoveryKey,
- }),
- parseAck: parseDiscardPrecreatedAck,
- forget: () => forgetPendingPrecreatedWorktree(worktreeAccountId, {
- sessionId,
- recoveryKey: pwt.recoveryKey,
- createdAt: pwt.createdAt ?? Date.now(),
- }),
- release: releasePrecreatedRegistration,
- });
- }
- return true;
- };
- // —— worktree 两步流第一步(对齐桌面远程流程 NewMakerDraftRoute:远程没有改已建
- // 会话 workingDir 的通道,顺序反过来 —— 先同步等工作端建好 worktree 拿路径,再以
- // 该路径 + 同一预生成 sessionId 走乐观管线)。worktree:create 对同 sessionId 重跑
- // 不幂等,不能放进管线的重试面 —— 失败(业务 {ok:false} / invoke 抛错)一律留在
- // 表单展示错误,不建会话(草稿原地保留,与桌面远程失败语义一致)。
- if (
- worktreeIntent.applicable
- && worktreeIntent.enabled
- && worktreeIntent.eligibility.status === 'eligible'
- ) {
- try {
- // suggest-name 失败不阻断:走 auto- 兜底名(对齐桌面 :1316)。
- if (!isCurrentOwner()) return;
- let suggested: string | null = null;
- try {
- suggested = await maker.worktree
- .suggestName(worktreeIntent.eligibility.baseRepo)
- .then((result) => result.name);
- } catch {
- suggested = null;
- }
- if (!isCurrentOwner()) return;
- if (!ensureDeviceAlive()) return;
- if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
- setError(t(resolveWorktreeCreateErrorKey()));
- return;
- }
- const recoveryKey = createNewSessionId();
- const createdAt = Date.now();
- releasePrecreatedRegistration = holdPrecreatedWorktreeRegistration(sessionId);
- // reservation 必须先于远端副作用持久化。首次写盘失败时绝不调用
- // worktree:create;volatile 镜像只负责阻止本进程继续制造第二个孤儿,
- // 不能冒充跨进程保证。
- const reservationRecorded = await registerPendingPrecreatedWorktree(
- worktreeAccountId,
- {
- sessionId,
- deviceId: selectedDeviceId,
- recoveryKey,
- createdAt,
- phase: 'reserved',
- },
- );
- if (!isCurrentOwner()) return;
- // ㉙ 写盘 reservation 后切设备 → 清掉这份 obligation(reserved 无远端
- // 目录,不产生孤儿,但会阻塞同设备下次创建的 recovery 直到被回收)。
- if (!ensureDeviceAlive()) {
- await forgetPendingPrecreatedWorktree(worktreeAccountId, {
- sessionId,
- recoveryKey,
- createdAt,
- }).catch(() => undefined);
- return;
- }
- if (!reservationRecorded) {
- setError(t('session.new.worktreeRecoveryStateFailed'));
- return;
- }
- if (!isCurrentOwner()) return;
- if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
- await forgetPendingPrecreatedWorktree(worktreeAccountId, {
- sessionId,
- recoveryKey,
- createdAt,
- });
- setError(t(resolveWorktreeCreateErrorKey()));
- return;
- }
- const createRequest = buildWorktreeCreateRequest({
- sessionId,
- eligibility: worktreeIntent.eligibility,
- sourceBranch: worktreeIntent.sourceBranch,
- suggestedName: suggested,
- recoveryKey,
- });
- const resp = parseWorktreeCreateResult(
- await maker.worktree.create(createRequest),
- createRequest,
- );
- if (!isCurrentOwner()) return;
- if (!resp) {
- setError(t('session.new.worktreeCleanupPending'));
- return;
- }
- if (!resp.ok) {
- await forgetPendingPrecreatedWorktree(worktreeAccountId, {
- sessionId,
- recoveryKey,
- createdAt,
- });
- if (!isCurrentOwner()) return;
- setError(formatWorktreeCreateFailure(resp.error));
- return;
- }
- precreatedWorktree = {
- path: resp.meta.path,
- recoveryKey,
- originalWorkingDir: effectiveDraft.workingDir,
- createdAt,
- };
- // ㉙ 远端目录已产生 → 切设备必须走 ledger 补偿(forget + 释放内存持有,
- // 远端目录留给下次 recovery 对账回收)。
- if (await abortIfDeviceSwitched()) return;
- // 回包后尽力把 path 补到账本;即使这次更新失败,首次已确认落盘的
- // recoveryKey reservation 仍足够让重启后的进程从被控端解析真实路径。
- await registerPendingPrecreatedWorktree(worktreeAccountId, {
- sessionId,
- deviceId: selectedDeviceId,
- path: precreatedWorktree.path,
- recoveryKey,
- createdAt,
- phase: 'precreated',
- });
- if (!isCurrentOwner()) return;
- if (await abortIfDeviceSwitched()) return;
- effectiveDraft = { ...effectiveDraft, workingDir: resp.meta.path };
- } catch {
- if (!isCurrentOwner()) return;
- // invoke 抛错时无法判断工作端是否已经完成创建;保留 reservation,
- // 交给当前进程重连或下次冷启动按 recoveryKey 精确对账。
- setError(t('session.new.worktreeCleanupPending'));
- return;
- }
- }
- if (useDurableCreation && precreatedWorktree) {
- const current = outboxRecoveryRef.current;
- if (!current?.creation || current.item.sessionId !== sessionId) throw new Error('OUTBOX_STALE_WRITE');
- const updated = await mobileDurableOutbox.update(current, {
- creation: { ...current.creation, draft: effectiveDraft }, suspended: !!current.creation.editReady,
- });
- outboxRecoveryRef.current = updated;
- if (!isCurrentOwner() || !ensureDeviceAlive()) return;
- }
+ const prepared = await prepareNewSessionCreation({
+ effectiveDraft,
+ outboxRecoveryRef,
+ selectedDeviceId,
+ selectedDeviceName,
+ authOwnerAtCreate,
+ worktreeAccountId,
+ creatingWorktree,
+ worktreeIntent,
+ isCurrentOwner,
+ ensureDeviceAlive,
+ isWorktreeCreateIntentCurrent,
+ runtimeOptions,
+ prePlanPermissionModeRef,
+ planModeCapability,
+ planModeDraftOn,
+ sendAttachments,
+ attachmentPreviews,
+ getUploadedSource,
+ releaseUploadedSources,
+ maker,
+ t,
+ setError,
+ setDraft,
+ resolveWorktreeCreateErrorKey,
+ onHoldDurableCreation: (release) => {
+ creationLeases.durable = release;
+ },
+ onHoldPrecreatedRegistration: (release) => {
+ creationLeases.precreated = release;
+ },
+ });
+ if (!prepared) return;
+ effectiveDraft = prepared.effectiveDraft;
+ const { sessionId, agentKindSnapshot, deviceIdSnapshot, firstMessageClientId,
+ legacyPlanRestore, useDurableCreation, precreatedWorktree, abortIfDeviceSwitched } = prepared;
// 提交点联合终检(Greptile/Codex review P1):目录就绪后的清理 effect 跑在渲染后,
// 用户可能在清理生效前点创建——创建路径自身必须守卫;来源失效时 model 随之一并
// 回退(其他来源顶替 / 首项 / 留空),并同步校准 effort、组合变化时 fastMode
@@ -4896,10 +4084,6 @@ export default function NewRemoteSessionScreen() {
// handoff(同一 turn)——杜绝「核对后让出微任务期间换代,再按旧目录应用」。
if (await abortIfDeviceSwitched()) return;
const guardDeviceId = deviceAtCreate;
- const guardSelected = () => ({
- model: effectiveDraft.model,
- providerId: effectiveDraft.providerId,
- });
// Agent 在另一台电脑运行:模型属于那台的目录,不按被控电脑的目录校准(由那台在运行时核对)。
const runGuard = () => effectiveDraft.agentDeviceId ? Promise.resolve({
rows: [] as readonly ProviderModelRow[], providers: [], catalogKnown: false, genAt: getDeviceProvidersGen(guardDeviceId),
@@ -4920,45 +4104,8 @@ export default function NewRemoteSessionScreen() {
}).sections),
});
const applyGuard = (g: SubmitGuardCatalog): void => {
- if (g.catalogKnown && modelNeedsReselection(g.visibilityOverrides, effectiveDraft.agentKind, effectiveDraft.model, effectiveDraft.providerId)) {
- throw new Error(t('session.common.modelHiddenReselect', { model: effectiveDraft.model }));
- }
- const resolved = resolveRecentModelAndProvider(
- g.rows,
- guardSelected(),
- effectiveDraft.agentKind,
- g.catalogKnown,
- g.providers,
- g.visibilityOverrides,
- );
- assertSubmitModelResolved(resolved, effectiveDraft.model);
- const pairChanged = resolved.model !== effectiveDraft.model || resolved.providerId !== effectiveDraft.providerId;
- // 目录就绪时**始终**按 fresh 精确行校准(codex review P2:来源未变时也按
- // 新目录校准运行选项)——provider revision 可能只改能力不删行(撤销 effort
- // 档位 / Fast 支持),组合不变沿用旧 effort/fastMode 会发送目录已不支持的
- // 参数被被控端拒绝。fail-open(catalogKnown=false)时 rows 不可信,保持
- // 信任语义(不校准,仅组合变化保守关 fast)。
- effectiveDraft = {
- ...effectiveDraft,
- ...resolved,
- ...(g.catalogKnown ? {
- effort: reconcileEffortAfterFallback(g.rows, resolved, effectiveDraft.effort),
- ...(effectiveDraft.fastMode && (
- pairChanged
- || !resolved.providerId
- || !isFastRestorable(
- effectiveDraft.agentKind,
- resolved.providerId,
- resolved.model,
- g.rows,
- targetAgentHasFast(guardDeviceId, effectiveDraft.agentKind),
- effectiveDraft.fastMode,
- )
- ) ? { fastMode: false } : {}),
- } : pairChanged ? {
- ...(effectiveDraft.fastMode ? { fastMode: false } : {}),
- } : {}),
- };
+ effectiveDraft = reconcileNewSessionSubmitDraft(effectiveDraft, g,
+ () => targetAgentHasFast(guardDeviceId, effectiveDraft.agentKind), t);
};
// 有界稳定循环:每轮 await 返回后同步核对 genAt,稳定才退出(≤3)。
// 哨兵初值必被首轮循环覆盖(for 循环体至少执行一次),消除 null 收窄。
@@ -5015,48 +4162,8 @@ export default function NewRemoteSessionScreen() {
: () => confirmAgentUnauthenticated(agentKindSnapshot, deviceIdSnapshot),
// 鉴权 fresh 之后联合校验 (model, providerId)(codex review P2):建链/鉴权
// 期间工作站可能已替换 provider——patch 覆盖本次创建,不再向已删除来源发。
- revalidateDraftAfterAuth: async (fresh) => {
- if (modelNeedsReselection(fresh.modelVisibilityOverrides, effectiveDraft.agentKind, effectiveDraft.model, effectiveDraft.providerId)) {
- throw new Error(t('session.common.modelHiddenReselect', { model: effectiveDraft.model }));
- }
- const rows = flattenProviderSections(buildMobileModelSections({
- providers: fresh.providers,
- agentKind: effectiveDraft.agentKind,
- visibilityOverrides: fresh.modelVisibilityOverrides,
- selectedModelId: effectiveDraft.model,
- selectedProviderId: effectiveDraft.providerId,
- }).sections);
- const resolved = resolveRecentModelAndProvider(
- rows,
- { model: effectiveDraft.model, providerId: effectiveDraft.providerId },
- effectiveDraft.agentKind,
- true,
- fresh.providers,
- fresh.modelVisibilityOverrides,
- );
- assertSubmitModelResolved(resolved, effectiveDraft.model);
- const pairChanged = resolved.model !== effectiveDraft.model
- || resolved.providerId !== effectiveDraft.providerId;
- // codex review P2:来源未变也按 fresh 精确行校准——fresh 目录就绪时始终
- // 重校准 effort + Fast 支持(provider revision 只改能力不删行:撤销档位/
- // Fast 时组合不变也要关),不得因 pairChanged=false 提前返回发旧参数。
- return {
- ...resolved,
- effort: reconcileEffortAfterFallback(rows, resolved, effectiveDraft.effort),
- ...(effectiveDraft.fastMode && (
- pairChanged
- || !resolved.providerId
- || !isFastRestorable(
- effectiveDraft.agentKind,
- resolved.providerId,
- resolved.model,
- rows,
- targetAgentHasFast(selectedDeviceId, effectiveDraft.agentKind),
- effectiveDraft.fastMode,
- )
- ) ? { fastMode: false } : {}),
- };
- },
+ revalidateDraftAfterAuth: async (fresh) => revalidateNewSessionDraftAfterAuth(effectiveDraft, fresh,
+ () => targetAgentHasFast(selectedDeviceId, effectiveDraft.agentKind), t),
authGateHint: agentAuthGateHint(agentKindSnapshot),
onUnauthenticated: () => evictDeviceProviders(deviceIdSnapshot),
isCurrentOwner,
@@ -5101,8 +4208,8 @@ export default function NewRemoteSessionScreen() {
const raw = formatRemoteError(err);
setError(raw);
} finally {
- releasePrecreatedRegistration?.();
- releaseDurableCreation?.();
+ creationLeases.precreated?.();
+ creationLeases.durable?.();
if (!handedOff) {
creatingRef.current = false;
setCreating(false);
@@ -5146,7 +4253,7 @@ export default function NewRemoteSessionScreen() {
worktreeBranchPreferenceSyncKey,
worktreeCaptionKey,
worktreeEnabled,
- captureWorktreeCreateIntent,
+ prepareWorktreeCreateIntent,
isWorktreeCreateIntentCurrent,
resolveWorktreeCreateErrorKey,
]);
@@ -5179,11 +4286,8 @@ export default function NewRemoteSessionScreen() {
setModelSheetOpen(true);
return;
}
- const worktreeIntent = captureWorktreeCreateIntent();
- if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
- setGoalError(t(resolveWorktreeCreateErrorKey()));
- return;
- }
+ const worktreeIntent = prepareWorktreeCreateIntent(key => setGoalError(t(key)));
+ if (!worktreeIntent) return;
// ㉙ 设备守卫入口(独立 review P1-1 + busy 泄漏):快照取自闭包 selectedDeviceId,
// 入口与 ref 核对必须发生在**加锁之前**——加锁后 return 会绕过 finally,busy
// 状态永久泄漏(独立 review round-20 Standards P1)。
@@ -5207,11 +4311,7 @@ export default function NewRemoteSessionScreen() {
let sessionCreateStarted = false;
const accountIdAtCreate = auth.user?.id?.trim() ?? '';
const authOwnerAtCreate = getMobileAuthOwner();
- const worktreeAccountId = authOwnerAtCreate.accountId;
- const isCurrentOwner = () => (
- authOwnerAtCreate.accountId === accountIdAtCreate
- && isMobileAuthOwnerCurrent(authOwnerAtCreate)
- );
+ const { isCurrentOwner, worktreeAccountId } = captureNewSessionOwner(authOwnerAtCreate, accountIdAtCreate);
// ㉙ 设备守卫全程化(独立 review P1-1/P1-2):此后每次 await 后、每个 device-scoped
// 副作用前、最终 createSession 前复核。
const ensureDeviceAlive = (): boolean => selectedDeviceRef.current === deviceAtCreate;
@@ -5453,10 +4553,6 @@ export default function NewRemoteSessionScreen() {
// 重跑 guard 继续 commit);apply 后零 await 至 createSession。
if (!ensureDeviceAlive()) return;
const guardDeviceId = deviceAtCreate;
- const guardSelected = () => ({
- model: effectiveDraft.model,
- providerId: effectiveDraft.providerId,
- });
// Agent 在另一台电脑运行:不按被控电脑的目录校准,也不按它的来源判登录(同 create())。
const runGuard = () => effectiveDraft.agentDeviceId ? Promise.resolve({
rows: [] as readonly ProviderModelRow[], providers: [], catalogKnown: false, genAt: getDeviceProvidersGen(guardDeviceId),
@@ -5475,44 +4571,8 @@ export default function NewRemoteSessionScreen() {
}).sections),
});
const applyGuard = (g: SubmitGuardCatalog): void => {
- if (g.catalogKnown && modelNeedsReselection(g.visibilityOverrides, effectiveDraft.agentKind, effectiveDraft.model, effectiveDraft.providerId)) {
- throw new Error(t('session.common.modelHiddenReselect', { model: effectiveDraft.model }));
- }
- const resolved = resolveRecentModelAndProvider(
- g.rows,
- guardSelected(),
- effectiveDraft.agentKind,
- g.catalogKnown,
- g.providers,
- g.visibilityOverrides,
- );
- assertSubmitModelResolved(resolved, effectiveDraft.model);
- const pairChanged = resolved.model !== effectiveDraft.model || resolved.providerId !== effectiveDraft.providerId;
- // codex review P2:目录就绪时**始终**按 fresh 精确行校准(来源未变也按新
- // 目录校准运行选项)——provider revision 只改能力不删行(撤销 effort 档位
- // /Fast 支持)时,组合不变沿用旧 effort/fastMode 会发送目录已不支持的参数
- // 被被控端拒绝。fail-open(catalogKnown=false)时 rows 不可信,保持信任语义。
- effectiveDraft = {
- ...effectiveDraft,
- ...resolved,
- ...(g.catalogKnown ? {
- effort: reconcileEffortAfterFallback(g.rows, resolved, effectiveDraft.effort),
- ...(effectiveDraft.fastMode && (
- pairChanged
- || !resolved.providerId
- || !isFastRestorable(
- effectiveDraft.agentKind,
- resolved.providerId,
- resolved.model,
- g.rows,
- targetAgentHasFast(guardDeviceId, effectiveDraft.agentKind),
- effectiveDraft.fastMode,
- )
- ) ? { fastMode: false } : {}),
- } : pairChanged ? {
- ...(effectiveDraft.fastMode ? { fastMode: false } : {}),
- } : {}),
- };
+ effectiveDraft = reconcileNewSessionSubmitDraft(effectiveDraft, g,
+ () => targetAgentHasFast(guardDeviceId, effectiveDraft.agentKind), t);
};
// ── prepare 段(可取消):连接 + abort 前置,终检循环每轮 await 后同步核对 genAt ──
await withTransientRemoteRetry(async () => {
@@ -5944,7 +5004,7 @@ export default function NewRemoteSessionScreen() {
worktreeApplicable,
worktreeEligibility,
worktreeEnabled,
- captureWorktreeCreateIntent,
+ prepareWorktreeCreateIntent,
isWorktreeCreateIntentCurrent,
resolveWorktreeCreateErrorKey,
]);
@@ -6477,7 +5537,7 @@ export default function NewRemoteSessionScreen() {
onCollapsedPress={composerPillOpen.onCollapsedPress}
expandToken={composerPillOpen.expandToken}
cardActive={composerCardActive}
- caretHidden={voiceIsListening}
+
cursorColor={colors.inputCaret}
inputRef={firstMessageInputRef}
leading={renderComposerCompactLeading()}
@@ -6487,7 +5547,7 @@ export default function NewRemoteSessionScreen() {
// 是这层输入区自身(TextInput 的 onPressIn),单行时只有 28pt。
inputFrameMinHeight={Platform.OS !== 'ios' && voiceIsListening ? MOBILE_COMPOSER_MIN_TOUCH_TARGET : undefined}
inputOverlay={renderComposerInputOverlay()}
- inputStyle={voiceIsListening && Platform.OS !== 'ios' ? styles.inputVoiceHidden : undefined}
+ {...newSessionVoiceComposerProps({ platform: Platform.OS, voiceIsListening, firstMessage: draft.firstMessage, firstMessageSelection, composerPlaceholder, voiceStopGestureSelectionGuardRef, voicePendingSelectionEchoesRef, finishVoiceRecording })}
inputTestID="newSession.firstMessageInput"
maxHeight={composerResize.inputMaxHeight}
multilineShape={!composerCardActive && composerInputIsMultiline}
@@ -6496,73 +5556,24 @@ export default function NewRemoteSessionScreen() {
// 失焦收起与「点别处收键盘」同语义:语音结束 hold 一并解除。
setComposerVoiceHoldArmed(false);
}}
- onChangeText={(text) => {
- if (text !== firstMessageRef.current) {
- voicePendingSelectionEchoesRef.current = [];
- if (voiceStopInFlightRef.current) voiceSelectionUserOwnedRef.current = true;
- }
- setFirstMessageDraft(text);
- }}
- onKeyPress={() => { voicePendingSelectionEchoesRef.current = []; }}
- onSelectionChange={(event) => {
- const selection = event.nativeEvent.selection;
- if (!voiceRecordingActiveRef.current && voiceStopGestureSelectionGuardRef.current) {
- voiceStopGestureSelectionGuardRef.current = false;
- return;
- }
- // Native may echo an earlier ASR/refinement update after JS has
- // already published the next one, even after stop() resolves.
- const pending = voicePendingSelectionEchoesRef.current;
- const echoIndex = pending.findIndex((value) =>
- value.start === selection.start && value.end === selection.end);
- if (echoIndex >= 0) {
- // Selection events can coalesce: acknowledging a newer write
- // also retires older writes that never emitted an event.
- pending.splice(0, echoIndex + 1);
- return;
- }
- // finishVoiceRecording marks recording inactive before awaiting
- // ASR/refinement teardown, so native cursor edits remain user-owned.
- if (!voiceRecordingActiveRef.current) {
- voicePendingSelectionEchoesRef.current = [];
- const previous = firstMessageSelectionRef.current;
- // A matching native echo of a controlled selection is not a user move.
- if (voiceStopInFlightRef.current
- && (selection.start !== previous.start || selection.end !== previous.end)) {
- voiceSelectionUserOwnedRef.current = true;
- }
- firstMessageSelectionRef.current = selection;
- setFirstMessageSelection(selection);
- }
- }}
+ onChangeText={text => changeNewSessionVoiceText(voiceSelectionInput, text)}
+
+ onSelectionChange={event => changeNewSessionVoiceSelection(voiceSelectionInput, event.nativeEvent.selection)}
onContentSizeChange={handleFirstMessageInputContentSizeChange}
onFocus={() => setFirstMessageInputFocused(true)}
onPasteImages={(uris) => void addPastedImageAttachments(uris)}
onPasteImagesLoading={beginPastePlaceholders}
onPasteImagesLoadFailed={failPastePlaceholders}
- onPressIn={() => {
- if (voiceIsListening) {
- voiceStopGestureSelectionGuardRef.current = true;
- setTimeout(() => {
- voiceStopGestureSelectionGuardRef.current = false;
- }, 0);
- void finishVoiceRecording();
- } else {
- // A new editing gesture can intentionally return to any old
- // controlled value; it must not be mistaken for its echo.
- voicePendingSelectionEchoesRef.current = [];
- }
- }}
- placeholder={voiceIsListening ? '' : composerPlaceholder}
+
placeholderTextColor={colors.textPlaceholder}
resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}
scrollEnabled={composerInputScrollEnabled}
- selection={firstMessageSelection}
+
selectionColor={colors.inputCaret}
testID="newSession.actions"
toolbar={renderComposerToolbar()}
trailing={composerCardActive || !composerShowCreateButton ? null : renderCreateButton()}
- value={draft.firstMessage}
+
voicePlacement={composerVoicePlacement}
floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}
/>
@@ -6686,7 +5697,6 @@ export default function NewRemoteSessionScreen() {
{contextSheetView === 'main' ? (
<>
-
<ContextSheetGroup label={Platform.OS === 'ios' && contextSheetMediaLibraryEnabled ? '' : t('session.common.groupAdd')}>
<ContextSheetRow
disabled={creating}
@@ -7789,12 +6799,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
lineHeight: lineHeight.caption,
minWidth: 0,
},
- inputVoiceHidden: {
- color: 'transparent',
- // Android Fabric can treat transparent text as an unset color and draw it black.
- // Keep layout/presses; iOS needs nonzero view opacity for native hit testing.
- ...(Platform.OS === 'android' ? { opacity: 0 } : {}),
- },
+
sendButton: {
alignItems: 'center',
backgroundColor: colors.cta,
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index f8682a5793..04e6afdefb 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -80,7 +80,20 @@ const loginFixturesStub = path.join(
'packages/auth-client/fixtures/loginScenarios.production-stub.ts',
);
+const devEndpointManifest = path.join(workspaceRoot, 'config/endpoint.dev.json');
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
+ // Metro collects static requires even in inactive env.ts branches. This private,
+ // gitignored manifest is only an input to explicitly selected CindyDev builds;
+ // Global/CN must work without it and must not bundle it when it happens to exist.
+ // Dev uses normal resolution, so a missing manifest still fails explicitly.
+ if (
+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION?.trim() !== 'dev' &&
+ path.resolve(path.dirname(context.originModulePath), moduleName) === devEndpointManifest
+ ) {
+ return { type: 'empty' };
+ }
+
if (moduleName === loginFixturesModule && process.env.NODE_ENV === 'production') {
return { type: 'sourceFile', filePath: loginFixturesStub };
}
diff --git a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
index 5446287d9f..721b97b17f 100644
--- a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
+++ b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
@@ -1,54 +1,60 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
-import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
-import { cindyMakeOutboxPolicy } from '@/session/cindyMakeOutboxPolicy';
-import { isDurableOutboxHandedOff, isDurableOutboxSettled, type DurableOutboxRecord } from '@/session/durableOutbox';
-import type { OutboxSessionPolicy } from '@/session/durableOutboxDelivery';
-
-const source = ts.createSourceFile('MobileOutboxBridge.tsx', readFileSync(resolve(
- process.cwd(), 'src/session/MobileOutboxBridge.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-const expressions = new Map<string, string>();
-const names = ['knownSession', 'hidden', 'invokeOwned', 'readSessionOnce', 'canRun', 'sessionPolicy'];
-function visit(node: ts.Node) {
- if ((ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)
- && ['canRun', 'sessionPolicy'].includes(node.name.getText(source))) && node.initializer
- && names.includes(node.name.getText(source))) expressions.set(node.name.getText(source), node.initializer.getText(source));
- ts.forEachChild(node, visit);
-}
-visit(source);
-for (const name of names) if (!expressions.has(name)) throw new Error('Missing outbox callback: ' + name);
-const compiled = ts.transpileModule(
- 'function create(deps) { const { remoteSessionStore, mobileDurableOutbox, latest, guard, AppState, CINDY_MAKE_ENABLED, isCindyMakeSource, isDurableOutboxSettled, isDurableOutboxHandedOff, cindyMakeOutboxPolicy, isCurrent } = deps;'
- + 'const sessionReads = new Map(); const SESSION_READ_REUSE_MS = 2000;'
- + ['knownSession', 'hidden', 'invokeOwned', 'readSessionOnce'].map(name => 'const ' + name + ' = ' + expressions.get(name) + ';').join('')
- + 'const needsReconciliation = () => true; const isDurableOutboxCreationHeld = () => false; const getNewSessionCreationTask = () => null;'
- + 'const maker = (record) => ({ getSession: (sessionId) => invokeOwned(record)(record.deviceId, "local-db:sessions:get", [sessionId]) });'
- + 'return { hidden, invokeOwned, canRun: ' + expressions.get('canRun') + ', sessionPolicy: ' + expressions.get('sessionPolicy') + ' }; }',
- { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
-).outputText;
+import type { DurableOutboxRecord } from '@/session/durableOutbox';
+import { createOutboxSessionAccess } from '@/session/mobileOutboxSessionAdapter';
function harness(sessions: Array<{ id: string; source?: string; deviceLinkDeviceId: string }>) {
const record = { deviceId: 'desktop', state: 'queued', uploads: [],
item: { sessionId: 'session', clientId: 'client', attachmentSlots: [] } } as unknown as DurableOutboxRecord;
- const invoke = vi.fn(async (_device: string, _channel: string, _args: unknown[], options: { preSend(): void }) => {
+ const invoke = vi.fn(async (_device: string, _channel: string, _args: unknown[] | undefined, options: { preSend(): void }) => {
options.preSend(); return { id: 'session', source: 'cc' };
});
const latest = { current: { link: { status: 'online', getPresenceAvailability: () => true, invoke } } };
- const deps = { remoteSessionStore: { getSessions: () => sessions }, mobileDurableOutbox: { getSnapshot: () => [record] },
- latest, guard: () => {}, AppState: { currentState: 'active' }, CINDY_MAKE_ENABLED, isCindyMakeSource,
- isDurableOutboxSettled, isDurableOutboxHandedOff, cindyMakeOutboxPolicy, isCurrent: () => true };
- const callbacks = new Function(compiled + '; return create;')()(deps) as {
- hidden(record: DurableOutboxRecord): boolean;
- canRun(record: DurableOutboxRecord): boolean;
- sessionPolicy(record: DurableOutboxRecord): Promise<OutboxSessionPolicy>;
- invokeOwned(record: DurableOutboxRecord): (device: string, channel: string, args: unknown[]) => Promise<unknown>;
- };
- return { record, callbacks, invoke, latest, deps };
+ const owner = { current: true, records: [record] };
+ const hasCreationTask = vi.fn(() => false);
+ const callbacks = createOutboxSessionAccess({
+ getSessions: () => sessions,
+ getRecords: () => owner.records,
+ guard: () => { if (!owner.current) throw new Error('OUTBOX_OWNER_CHANGED'); },
+ isCurrent: () => owner.current,
+ isForeground: () => true,
+ canConnect: () => latest.current.link.status === 'online' && latest.current.link.getPresenceAvailability() !== false,
+ isCreationHeld: () => false,
+ hasCreationTask,
+ needsReconciliation: () => true,
+ invoke: (deviceId, channel, args, options) => latest.current.link.invoke(deviceId, channel, args, options),
+ readSession: record => callbacks.invokeOwned(record)(record.deviceId, 'local-db:sessions:get', [record.item.sessionId]),
+ });
+ return { record, callbacks, invoke, latest, owner, hasCreationTask };
}
describe('Cindy Make outbox bridge guards', () => {
+ // Unit: extracting the bridge must retain both ownership barriers around a
+ // delayed RPC. Source-visibility tests alone do not cover removal/account changes.
+ it('does not send a record removed while the transport was waiting', async () => {
+ const { record, callbacks, invoke, owner } = harness([]);
+ const sent = vi.fn();
+ invoke.mockImplementationOnce(async (_device, _channel, _args, options) => {
+ owner.records = [];
+ options.preSend();
+ sent();
+ return { id: 'session', source: 'cc' };
+ });
+ await expect(callbacks.invokeOwned(record)('desktop', 'maker:input:enqueue', ['session']))
+ .rejects.toThrow('OUTBOX_STALE_WRITE');
+ expect(sent).not.toHaveBeenCalled();
+ });
+
+ it('rejects a late reply after the account owner changes', async () => {
+ const { record, callbacks, invoke, owner } = harness([]);
+ invoke.mockImplementationOnce(async (_device, _channel, _args, options) => {
+ options.preSend();
+ owner.current = false;
+ return { id: 'session', source: 'cc' };
+ });
+ await expect(callbacks.invokeOwned(record)('desktop', 'local-db:sessions:get', ['session']))
+ .rejects.toThrow('OUTBOX_OWNER_CHANGED');
+ });
+
it.each(['cindy-make', 'cindy-make-merge'])('selects a suspended hidden %s record for local cleanup even offline', async source => {
const { record, callbacks, invoke, latest } = harness([{ id: 'session', source, deviceLinkDeviceId: 'desktop' }]);
record.suspended = true;
@@ -83,10 +89,12 @@ describe('Cindy Make outbox bridge guards', () => {
});
it('keeps ordinary offline records suspended instead of deleting or delivering them', () => {
- const { record, callbacks, latest } = harness([{ id: 'session', source: 'cc', deviceLinkDeviceId: 'desktop' }]);
+ const { record, callbacks, latest, hasCreationTask } = harness([{ id: 'session', source: 'cc', deviceLinkDeviceId: 'desktop' }]);
latest.current.link.status = 'offline';
expect(callbacks.hidden(record)).toBe(false);
expect(callbacks.canRun(record)).toBe(false);
+ // Creation lookup can scan the ledger; offline records must short-circuit it.
+ expect(hasCreationTask).not.toHaveBeenCalled();
latest.current.link.status = 'online';
record.suspended = true;
expect(callbacks.canRun(record)).toBe(false);
diff --git a/apps/mobile/src/__tests__/envBundleTransform.test.ts b/apps/mobile/src/__tests__/envBundleTransform.test.ts
index f2ecf371ea..08de4ba565 100644
--- a/apps/mobile/src/__tests__/envBundleTransform.test.ts
+++ b/apps/mobile/src/__tests__/envBundleTransform.test.ts
@@ -1,54 +1,205 @@
import { createRequire } from 'node:module';
import { resolve } from 'node:path';
import { runInNewContext } from 'node:vm';
+import type { CustomResolutionContext } from '@expo/metro/metro-resolver';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import metroConfig from '../../metro.config.js';
const require = createRequire(import.meta.url);
-const babel = require('@babel/core') as {
- transformFileSync(filename: string, options: Record<string, unknown>): { code?: string };
-};
+const babel = require('@babel/core') as typeof import('@babel/core');
const expoPreset = require('babel-preset-expo');
+const collectDependencies =
+ require('@expo/metro/metro/ModuleGraph/worker/collectDependencies')
+ .default as typeof import('@expo/metro/metro/ModuleGraph/worker/collectDependencies').default;
+const { resolve: metroResolve } =
+ require('@expo/metro/metro-resolver') as typeof import('@expo/metro/metro-resolver');
+const resolveMobileModule = metroConfig.resolver.resolveRequest!;
+const filename = resolve(process.cwd(), 'src/config/env.ts');
+
+function transformEnv(isProd: boolean) {
+ const caller = { name: 'metro', platform: 'android', isDev: !isProd };
+ return babel.transformFileSync(filename, {
+ ast: true,
+ babelrc: false,
+ configFile: false,
+ filename,
+ envName: isProd ? 'production' : 'development',
+ caller,
+ presets: [[expoPreset, { platform: 'android' }]],
+ })!;
+}
+
+function endpointResolutionContext(
+ isProd: boolean,
+ privateManifestPresent: boolean,
+): CustomResolutionContext {
+ const files = new Set([
+ resolve(process.cwd(), '../../config/endpoint.json'),
+ resolve(process.cwd(), '../../config/endpoint.global.json'),
+ ...(privateManifestPresent
+ ? [resolve(process.cwd(), '../../config/endpoint.dev.json')]
+ : []),
+ ]);
+ return {
+ originModulePath: filename,
+ dev: !isProd,
+ resolveRequest: metroResolve,
+ fileSystemLookup: (filePath) =>
+ files.has(filePath)
+ ? { exists: true, type: 'f', realPath: filePath }
+ : { exists: false },
+ doesFileExist: (filePath) => files.has(filePath),
+ getPackage: () => null,
+ getPackageForModule: () => null,
+ assetExts: new Set(),
+ sourceExts: ['json'],
+ mainFields: [],
+ allowHaste: false,
+ customResolverOptions: {},
+ disableHierarchicalLookup: true,
+ extraNodeModules: {},
+ nodeModulesPaths: [],
+ preferNativePlatform: false,
+ resolveAsset: () => null,
+ redirectModulePath: (modulePath) => modulePath,
+ resolveHasteModule: () => null,
+ resolveHastePackage: () => null,
+ unstable_conditionNames: [],
+ unstable_conditionsByPlatform: {},
+ unstable_enablePackageExports: false,
+ unstable_incrementalResolution: false,
+ unstable_logWarning: () => {},
+ };
+}
afterEach(() => vi.unstubAllEnvs());
describe('mobile endpoint overrides after Expo bundle transform', () => {
- it.each([false, true])('keeps explicit endpoints without a runtime shell env (production=%s)', (isProd) => {
- const env = {
- EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
- EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'http://localhost:3344',
- EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL: 'http://localhost:3335',
- };
- for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value);
- const filename = resolve(process.cwd(), 'src/config/env.ts');
- const transformed = babel.transformFileSync(filename, {
- babelrc: false, configFile: false, filename,
- envName: isProd ? 'production' : 'development',
- caller: { name: 'metro', platform: 'android', isDev: !isProd },
- presets: [[expoPreset, { platform: 'android' }]],
- });
- expect(transformed.code).toBeTruthy();
- const exports: Record<string, unknown> = {};
- runInNewContext(transformed.code!, {
- exports, process: { env: {} }, __DEV__: false,
- require(id: string) {
- if (id.startsWith('@babel/runtime/')) return require(id);
- if (id === 'expo/virtual/env') return { env };
- if (id === 'expo-application') return {};
- if (id === 'expo-constants') return { expoConfig: { extra: { xdtProductionEnv: {
- EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
- EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'https://fallback.example.invalid',
- } } } };
- if (id === '@cindy/maker-shared/client-endpoints') return {};
- if (id === './endpointManifestLoader') return {
- resolveMobileEndpointManifest() {
- throw new Error('Importing endpoint overrides must not fetch a manifest');
- },
- };
- throw new Error(`Unexpected import: ${id}`);
- },
+ it.each([false, true])(
+ 'keeps explicit endpoints without a runtime shell env (production=%s)',
+ (isProd) => {
+ const env = {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
+ EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'http://localhost:3344',
+ EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL: 'http://localhost:3335',
+ };
+ for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value);
+ const transformed = transformEnv(isProd);
+ expect(transformed.code).toBeTruthy();
+ const exports: Record<string, unknown> = {};
+ runInNewContext(transformed.code!, {
+ exports,
+ process: { env: {} },
+ __DEV__: false,
+ require(id: string) {
+ if (id.startsWith('@babel/runtime/')) return require(id);
+ if (id === 'expo/virtual/env') return { env };
+ if (id === 'expo-application') return {};
+ if (id === 'expo-constants')
+ return {
+ expoConfig: {
+ extra: {
+ xdtProductionEnv: {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
+ EXPO_PUBLIC_CINDY_AUTH_BASE_URL:
+ 'https://fallback.example.invalid',
+ },
+ },
+ },
+ };
+ if (id === '@cindy/maker-shared/client-endpoints') return {};
+ if (id === './endpointManifestLoader')
+ return {
+ resolveMobileEndpointManifest() {
+ throw new Error(
+ 'Importing endpoint overrides must not fetch a manifest',
+ );
+ },
+ };
+ throw new Error(`Unexpected import: ${id}`);
+ },
+ });
+ expect(exports.AUTH_REGION).toBe('global');
+ expect(exports.AUTH_API_BASE_URL).toBe(
+ env.EXPO_PUBLIC_CINDY_AUTH_BASE_URL,
+ );
+ expect(exports.DEVICE_LINK_API_BASE_URL).toBe(
+ env.EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL,
+ );
+ },
+ );
+
+ // Regression: clean worktrees have no private endpoint.dev.json. Runtime-only
+ // env tests miss Metro collecting every static require, even in inactive branches.
+ // Unit: use the real Expo transform, Metro collector and app resolver with an
+ // in-memory filesystem; no Metro server, private configuration or device required.
+ it.each([
+ ['global', false],
+ ['cn', false],
+ ['global', true],
+ ['cn', true],
+ ] as const)(
+ 'bundles %s without requiring or embedding private dev endpoints (production=%s)',
+ (region, isProd) => {
+ vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', region);
+ const { dependencies } = collectDependencies(transformEnv(isProd).ast!, {
+ asyncRequireModulePath: 'metro-runtime/src/modules/asyncRequire',
+ dependencyMapName: null,
+ dynamicRequires: 'reject',
+ inlineableCalls: [],
+ keepRequireNames: true,
+ allowOptionalDependencies: false,
+ unstable_allowRequireContext: false,
+ });
+ const manifests = dependencies.filter(({ name }) =>
+ name.includes('/config/endpoint'),
+ );
+ expect(manifests).toHaveLength(3);
+ for (const privateManifestPresent of [false, true]) {
+ const context = endpointResolutionContext(
+ isProd,
+ privateManifestPresent,
+ );
+ const resolutions = manifests.map(({ name }) =>
+ resolveMobileModule(context, name, 'android'),
+ );
+ expect(
+ resolutions
+ .filter((result) => result.type === 'sourceFile')
+ .map((result) => result.filePath)
+ .sort(),
+ ).toEqual(
+ [
+ resolve(process.cwd(), '../../config/endpoint.global.json'),
+ resolve(process.cwd(), '../../config/endpoint.json'),
+ ].sort(),
+ );
+ expect(
+ resolutions.filter((result) => result.type === 'empty'),
+ ).toHaveLength(1);
+ }
+ },
+ );
+
+ it('keeps explicit dev builds on their private manifest and fails if it is missing', () => {
+ vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', 'dev');
+ const moduleName = '../../../../config/endpoint.dev.json';
+ expect(
+ resolveMobileModule(
+ endpointResolutionContext(false, true),
+ moduleName,
+ 'ios',
+ ),
+ ).toEqual({
+ type: 'sourceFile',
+ filePath: resolve(process.cwd(), '../../config/endpoint.dev.json'),
});
- expect(exports.AUTH_REGION).toBe('global');
- expect(exports.AUTH_API_BASE_URL).toBe(env.EXPO_PUBLIC_CINDY_AUTH_BASE_URL);
- expect(exports.DEVICE_LINK_API_BASE_URL).toBe(env.EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL);
+ expect(() =>
+ resolveMobileModule(
+ endpointResolutionContext(false, false),
+ moduleName,
+ 'ios',
+ ),
+ ).toThrow(/endpoint\.dev\.json/);
});
});
diff --git a/apps/mobile/src/__tests__/fixtures/newSession.ts b/apps/mobile/src/__tests__/fixtures/newSession.ts
new file mode 100644
index 0000000000..4eaf500b69
--- /dev/null
+++ b/apps/mobile/src/__tests__/fixtures/newSession.ts
@@ -0,0 +1,36 @@
+import {
+ DEFAULT_NEW_SESSION_DRAFT,
+ type NewSessionDraft,
+} from "@/session/newSession";
+import type { RemoteSerializedAttachment } from "@/session/types";
+
+export function newSessionDraft(
+ patch: Partial<NewSessionDraft> = {},
+): NewSessionDraft {
+ return { ...DEFAULT_NEW_SESSION_DRAFT, ...patch };
+}
+
+export function newSessionAttachment(
+ patch: Partial<RemoteSerializedAttachment> = {},
+): RemoteSerializedAttachment {
+ return {
+ id: "photo",
+ path: "oss://photo",
+ name: "photo.png",
+ ext: "png",
+ size: 3,
+ category: "image",
+ mimeType: "image/png",
+ ...patch,
+ };
+}
+
+export function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 3bc6625e96..922166d6b3 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1,3 +1,5 @@
+import { reconcileNewSessionCatalogDraft, reconcileNewSessionSubmitDraft, revalidateNewSessionDraftAfterAuth, restoreNewSessionFastPreference } from '@/session/newSessionRuntimeReconciliation';
+import { newSessionDraft } from './fixtures/newSession';
import { modelNeedsReselection } from '../session/modelReselection';
import { isCindyAutoModelId } from '@cindy/model-providers/provider-identity';
import { buildMobileModelSections, flattenProviderSections, isFastRestorable } from '../session/providerModelSections';
@@ -51,16 +53,24 @@ import {
import type { DeviceProvidersPayload } from '@/device-link/deviceProvidersCache';
import type { ProviderModelRow } from '@/session/providerModelSections';
import type { RemoteSession } from '@/session/types';
+import type { NewSessionDraft, SubmitGuardCatalog } from '@/session/newSession';
// Windows checkout(core.autocrlf)下源码是 CRLF;统一归一成 LF,含 \n 的多行片段断言才跨平台成立。
const readTextLf = (...args: Parameters<typeof readFileSync>): string =>
String(readFileSync(...args)).replace(/\r\n/g, '\n');
// Existing source contracts follow the extracted hooks; load their text once.
+const newSessionPageSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
const newSessionSources = [
'app/sessions/new.tsx',
'src/session/useNewSessionDefaultSelection.ts',
'src/session/useNewSessionHostDefaults.ts',
+ 'src/session/newSessionForm.ts',
+ 'src/session/useNewSessionWorkspace.ts',
+ 'src/session/useNewSessionWorktreeSync.ts',
+ 'src/session/newSessionVoiceInput.ts',
+ 'src/session/prepareNewSessionCreation.ts',
+ 'src/session/newSessionRuntimeReconciliation.ts',
].map(path => readTextLf(resolve(process.cwd(), path), 'utf8')).join('\n');
// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。
@@ -557,9 +567,14 @@ describe('isNewSessionRuntimePending', () => {
expect(() => assertSubmitModelResolved({ model: 'claude-opus-5-5' }, 'claude-opus-5-5')).not.toThrow();
expect(() => assertSubmitModelResolved({ model: '' }, 'delisted-model'))
.toThrow('delisted-model 在这台电脑上已不可用,请重新选择模型后再发送。');
- // 三处提交终检(创建前两处 + 鉴权后重验)都要经过这道拦截。
- const source = newSessionSources;
- expect(source.split('assertSubmitModelResolved(resolved, effectiveDraft.model);').length - 1).toBe(3);
+ // Normal/goal submission share one decision; auth refresh reuses it. Test
+ // the observable rejection, not how many copies of the assertion exist.
+ const draft = newSessionDraft({ agentKind: 'codex', model: 'delisted-model', providerId: 'gone' });
+ expect(() => reconcileNewSessionSubmitDraft(draft, {
+ rows: [], providers: [], catalogKnown: true, genAt: 0,
+ }, () => false, key => key)).toThrow('delisted-model');
+ expect(() => revalidateNewSessionDraftAfterAuth(draft, { providers: [] }, () => false, key => key))
+ .toThrow('delisted-model');
});
});
@@ -2022,7 +2037,10 @@ describe('new session model', () => {
});
describe('new session composer surface', () => {
- it('keeps the controlled caret at the end after palette insertion and draft restore', () => {
+ // The native caret may echo before a render; these screen-only callbacks must
+ // publish text first. Restored text/caret behavior runs through newSessionForm
+ // in newSessionDraftRecovery.test.ts and newSessionIncomingShare.test.ts.
+ it('updates composer text before the controlled caret on slash or mention insertion', () => {
const newSource = newSessionSources;
const slashStart = newSource.indexOf('const selectSlashCommand = useCallback');
const slashEnd = newSource.indexOf('const selectAtResource = useCallback', slashStart);
@@ -2030,9 +2048,6 @@ describe('new session composer surface', () => {
const atStart = slashEnd;
const atEnd = newSource.indexOf('const removeAttachment = useCallback', atStart);
const atSource = newSource.slice(atStart, atEnd);
- const restoreStart = newSource.indexOf('const restoreCreationDraft = useCallback');
- const restoreEnd = newSource.indexOf('setDraft(recovered);', restoreStart);
- const restoreSource = newSource.slice(restoreStart, restoreEnd);
for (const source of [slashSource, atSource]) {
expect(source).toContain('const current = firstMessageRef.current;');
@@ -2041,11 +2056,6 @@ describe('new session composer surface', () => {
source.indexOf('setFirstMessageSelection(selection)'),
);
}
- expect(restoreSource).toContain('firstMessageRef.current = recovered.firstMessage;');
- expect(restoreSource).toContain('firstMessageSelectionRef.current = selection;');
- expect(restoreSource).toContain('setFirstMessageSelection(selection);');
- expect(newSource).toContain('restoreCreationDraft(stashed.draft, [...stashed.attachments], undefined, stashed.deviceId || undefined);');
- expect(newSource).toContain('restoreCreationDraft(record.creation.draft,');
});
it('does not double-apply the Android safe-area inset to the top navigation', () => {
@@ -2068,321 +2078,26 @@ describe('new session composer surface', () => {
expect(newSource).not.toContain("Platform.OS === 'ios' ? 'padding' : undefined");
});
- it('uses the shared mobile composer row rather than a separate input implementation', () => {
- const newSource = newSessionSources;
- const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
- const sharedSource = readTextLf(resolve(process.cwd(), 'src/session/MobileComposerInputRow.tsx'), 'utf8');
- const newComposerStart = newSource.indexOf('<MobileComposerInputRow');
- const newComposerEnd = newSource.indexOf('\n />', newComposerStart) + '\n />'.length;
- const newComposerSource = newSource.slice(newComposerStart, newComposerEnd);
- const attachmentButtonStart = newSource.indexOf('const renderAttachmentToggleButton = () => (');
- const attachmentButtonEnd = newSource.indexOf('const renderCreateButton = () => (', attachmentButtonStart);
- const attachmentButtonSource = newSource.slice(attachmentButtonStart, attachmentButtonEnd);
- const createButtonStart = newSource.indexOf('const renderCreateButton = () => (');
- const createButtonEnd = newSource.indexOf('// 聚焦卡片形态的底部工具排', createButtonStart);
- const createButtonSource = newSource.slice(createButtonStart, createButtonEnd);
- const composerIconButtonStart = newSource.indexOf('composerIconButton: {');
- const composerIconButtonEnd = newSource.indexOf('composerCompactLeading:', composerIconButtonStart);
- const composerIconButtonStyle = newSource.slice(composerIconButtonStart, composerIconButtonEnd);
- const modelPillStart = newSource.indexOf('modelPill: {');
- const modelPillEnd = newSource.indexOf('modelPillText:', modelPillStart);
- const modelPillStyle = newSource.slice(modelPillStart, modelPillEnd);
- const modelPillTextStart = newSource.indexOf('modelPillText: {');
- const modelPillTextEnd = newSource.indexOf('inputVoiceHidden:', modelPillTextStart);
- const modelPillTextStyle = newSource.slice(modelPillTextStart, modelPillTextEnd);
- const voiceDraftTextStart = newSource.indexOf('voiceDraftText: {');
- const voiceDraftTextEnd = newSource.indexOf('voiceDraftListeningPrompt:', voiceDraftTextStart);
- const voiceDraftTextStyle = newSource.slice(voiceDraftTextStart, voiceDraftTextEnd);
- const sendButtonStart = newSource.indexOf('sendButton: {');
- const sendButtonEnd = newSource.indexOf('sendButtonDisabled:', sendButtonStart);
- const sendButtonStyle = newSource.slice(sendButtonStart, sendButtonEnd);
- const sendButtonDisabledStart = newSource.indexOf('sendButtonDisabled: {');
- const sendButtonDisabledEnd = newSource.indexOf('sendButtonPressed:', sendButtonDisabledStart);
- const sendButtonDisabledStyle = newSource.slice(sendButtonDisabledStart, sendButtonDisabledEnd);
- const voiceButtonStart = newSource.indexOf('const renderComposerVoiceButton = (buttonStyle?: StyleProp<ViewStyle>) => (');
- const voiceButtonEnd = newSource.indexOf('// 切 agent:', voiceButtonStart);
- const voiceButtonSource = newSource.slice(voiceButtonStart, voiceButtonEnd);
- const storedAgentStart = newSource.indexOf('const storedAgentKind = newSessionPreferences?.agentKind;');
- const storedAgentEnd = newSource.indexOf('// 新建任务默认运行配置', storedAgentStart);
- const storedAgentSource = newSource.slice(storedAgentStart, storedAgentEnd);
- const selectDeviceStart = newSource.indexOf('const selectDevice = useCallback((option: NewSessionDeviceOption) => {');
- const selectDeviceEnd = newSource.indexOf('// 切 agent:', selectDeviceStart);
- const selectDeviceSource = newSource.slice(selectDeviceStart, selectDeviceEnd);
- const selectWorkingDirStart = newSource.indexOf('const selectWorkingDir = useCallback((workingDir: string) => {');
- const selectDialogueWorkspaceStart = newSource.indexOf('const selectDialogueWorkspace = useCallback(() => {');
- const selectRecentProjectStart = newSource.indexOf('const selectRecentProject = useCallback((workingDir: string) => {');
- const openProjectBrowseStart = newSource.indexOf('const openProjectBrowse = useCallback(() => {');
- const selectWorkingDirSource = newSource.slice(selectWorkingDirStart, selectDialogueWorkspaceStart);
- const selectDialogueWorkspaceSource = newSource.slice(selectDialogueWorkspaceStart, selectRecentProjectStart);
- const selectRecentProjectSource = newSource.slice(selectRecentProjectStart, openProjectBrowseStart);
- const browseHiddenToggleStyleStart = newSource.indexOf('browseHiddenToggle: {');
- const browseHiddenToggleStyleEnd = newSource.indexOf('browseCheckbox: {', browseHiddenToggleStyleStart);
- const browseHiddenToggleStyle = newSource.slice(browseHiddenToggleStyleStart, browseHiddenToggleStyleEnd);
- const createStart = newSource.indexOf('const createMessageSession = useCallback(async () => {');
- const createEnd = newSource.indexOf('const createGoalSession = useCallback', createStart);
- expect(createStart).toBeGreaterThan(-1);
- expect(createEnd).toBeGreaterThan(createStart);
- const createSource = newSource.slice(createStart, createEnd);
- const dispatchStart = newSource.indexOf('const create = useCallback(async () => {', createEnd);
- expect(dispatchStart).toBeGreaterThan(createEnd);
- const dispatchEnd = newSource.indexOf('const goalDraftCommand', dispatchStart);
- expect(dispatchEnd).toBeGreaterThan(dispatchStart);
- const dispatchSource = newSource.slice(dispatchStart, dispatchEnd);
- expect(dispatchSource).toContain("if (parsed?.name !== 'goal' || pendingGoalSkillRef.current === 'goal')");
- expect(dispatchSource).toContain('await createMessageSession();');
-
- expect(newSource).toContain("MobileComposerInputRow,");
- expect(sessionSource).toContain("MobileComposerInputRow,");
- expect(newSource).toContain("import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';");
- expect(newSource).toContain("const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteString(params.visualFocusComposer) === '1';");
- expect(newSource).toContain('const visualInitialDraft = MOBILE_VISUAL_MOCK_ENABLED ? readRouteString(params.visualDraft) : null;');
- expect(newSource).toContain('firstMessage: visualInitialDraft ?? readRouteString(params.draft) ?? (isRemoteTaskSuggestionId(params.suggestion)');
- expect(newSource).toContain('t(`devices.list.taskSuggestions.items.${params.suggestion}.prompt`)');
- expect(newSource).toContain(': DEFAULT_NEW_SESSION_DRAFT.firstMessage)');
- expect(newComposerSource).toContain('inputTestID="newSession.firstMessageInput"');
- expect(newComposerSource).toContain('autoFocus={visualFocusComposer}');
- expect(newComposerSource).toContain('maxHeight={composerResize.inputMaxHeight}');
- expect(newComposerSource).toContain('inputFrameAnimatedStyle={composerResize.frameStyle}');
- expect(newSource).toContain('gesture={composerResize.gesture}');
- expect(newComposerSource).toContain('resizeHandle={composerCardActive ? renderComposerResizeHandle() : null}');
- expect(newComposerSource).toContain('cardActive={composerCardActive}');
- expect(newComposerSource).toContain('toolbar={renderComposerToolbar()}');
- expect(newComposerSource).toContain('voicePlacement={composerVoicePlacement}');
- expect(newComposerSource).toContain('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
- expect(newComposerSource).toContain('cursorColor={colors.inputCaret}');
- expect(newComposerSource).toContain('selectionColor={colors.inputCaret}');
- expect(newComposerSource).toContain('inputRef={firstMessageInputRef}');
- expect(newComposerSource).toContain('inputOverlay={renderComposerInputOverlay()}');
- expect(newComposerSource).toContain("inputStyle={voiceIsListening && Platform.OS !== 'ios' ? styles.inputVoiceHidden : undefined}");
- expect(newComposerSource).toContain('setFirstMessageDraft(text);');
- expect(newComposerSource).toContain('onContentSizeChange={handleFirstMessageInputContentSizeChange}');
- expect(newComposerSource).toContain("placeholder={voiceIsListening ? '' : composerPlaceholder}");
- expect(newComposerSource).toContain('scrollEnabled={composerInputScrollEnabled}');
- expect(newComposerSource).toContain('trailing={composerCardActive || !composerShowCreateButton ? null : renderCreateButton()}');
- expect(newComposerSource).toContain('leading={renderComposerCompactLeading()}');
- expect(newSource).toContain('const renderComposerCompactLeading = () => (');
- expect(newSource).not.toContain('styles.composerCompactAttachmentSlot');
- expect(newSource).toContain('styles.composerCompactAttachmentHit');
- expect(newSource).not.toContain('styles.composerCompactAttachmentHitArea');
- expect(newSource).toContain('pointerEvents="none"');
- expect(newSource).toContain('testID="newSession.attachmentToggleButton"');
- expect(newSource).toContain('height: MOBILE_COMPOSER_MIN_TOUCH_TARGET');
- expect(newSource).toContain('width: MOBILE_COMPOSER_MIN_TOUCH_TARGET');
- expect(newSource).toContain('minWidth: MOBILE_COMPOSER_MIN_TOUCH_TARGET');
- expect(newSource).not.toContain('marginVertical: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
- expect(newSource).not.toContain('marginHorizontal: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
- expect(newSource).not.toContain('left: (MOBILE_COMPOSER_CONTROL_SIZE - MOBILE_COMPOSER_MIN_TOUCH_TARGET) / 2');
- expect(newSource).toContain('const renderComposerToolbar = () => (');
- // 左侧组包住 [+][权限][计划][模型],再接 spacer;右段 语音占位 → 创建。
- const newToolbarStart = newSource.indexOf('const renderComposerToolbar = () => (');
- const newToolbarEnd = newSource.indexOf('const renderComposerInputOverlay', newToolbarStart);
- const newToolbarSource = newSource.slice(newToolbarStart, newToolbarEnd);
- const newToolbarLeftGroupStart = newToolbarSource.indexOf('<ComposerToolbarLeftGroup testID="newSession.composerToolbarLeft">');
- const newToolbarLeftGroupEnd = newToolbarSource.indexOf('</ComposerToolbarLeftGroup>');
- const newToolbarModelIndex = newToolbarSource.indexOf('testID="newSession.modelIndicator"');
- const newToolbarSpacerIndex = newToolbarSource.indexOf('<ComposerToolbarSpacer />');
- const newToolbarVoiceSlotIndex = newToolbarSource.indexOf('<ComposerToolbarVoiceSlot width={voiceRecordingTimer.pillWidth} />');
- expect(newToolbarLeftGroupStart).toBeGreaterThan(-1);
- expect(newToolbarModelIndex).toBeGreaterThan(newToolbarLeftGroupStart);
- expect(newToolbarLeftGroupEnd).toBeGreaterThan(newToolbarModelIndex);
- expect(newToolbarSpacerIndex).toBeGreaterThan(newToolbarLeftGroupEnd);
- expect(newToolbarVoiceSlotIndex).toBeGreaterThan(newToolbarSpacerIndex);
- expect(newSource).toContain('PaperPlaneIcon');
- expect(newSource).not.toContain('ArrowUp');
- expect(attachmentButtonSource).toContain('contextSheetOpen && styles.composerIconButtonActive');
- expect(attachmentButtonSource).toContain('color={contextSheetOpen ? colors.textPrimary : colors.textSecondary}');
- expect(attachmentButtonSource).toContain('size={iconSize.sm}');
- expect(createButtonSource).toContain('<PaperPlaneIcon');
- expect(createButtonSource).toContain('size={iconSize.lg}');
- expect(createButtonSource).toContain('color={canCreate ? colors.ctaText : colors.textSecondary}');
- expect(createButtonSource).toContain('<ActivityIndicator color={colors.textSecondary} size="small" />');
- expect(composerIconButtonStyle).toContain('backgroundColor: colors.sheetActionSurface');
- expect(composerIconButtonStyle).toContain('borderColor: colors.sheetActionBorder');
- expect(composerIconButtonStyle).toContain('borderWidth: StyleSheet.hairlineWidth');
- expect(composerIconButtonStyle).toContain('height: MOBILE_COMPOSER_CONTROL_SIZE');
- expect(composerIconButtonStyle).toContain('width: MOBILE_COMPOSER_CONTROL_SIZE');
- expect(modelPillStyle).toContain('backgroundColor: colors.sheetActionSurface');
- expect(modelPillStyle).toContain('borderColor: colors.sheetActionBorder');
- expect(modelPillStyle).toContain('borderRadius: radius.pill');
- expect(modelPillStyle).toContain('borderWidth: StyleSheet.hairlineWidth');
- expect(modelPillStyle).toContain('minHeight: MOBILE_COMPOSER_CONTROL_SIZE');
- expect(modelPillStyle).toContain('paddingHorizontal: spacing.md');
- expect(modelPillTextStyle).toContain('color: colors.textPrimary');
- expect(modelPillTextStyle).toContain('fontSize: typeScale.caption');
- expect(modelPillTextStyle).toContain('fontWeight: fontWeight.medium');
- // 输入框字号档由 MobileComposerInputRow 统一持有(MOBILE_COMPOSER_DRAFT_TEXT_STYLE),
- // 页面不再覆盖;语音草稿覆盖层必须引用同一档,否则换行位置与输入框错开(见
- // composerVoiceDraftMetrics.test.ts)。
- expect(newSource).not.toContain('sessionComposerInput');
- expect(voiceDraftTextStyle).toContain('...MOBILE_COMPOSER_DRAFT_TEXT_STYLE');
- expect(sendButtonStyle).toContain('backgroundColor: colors.cta');
- expect(sendButtonStyle).toContain('borderColor: colors.cta');
- expect(sendButtonStyle).toContain('borderWidth: StyleSheet.hairlineWidth');
- expect(sendButtonStyle).toContain('height: MOBILE_COMPOSER_CONTROL_SIZE');
- expect(sendButtonStyle).toContain('width: MOBILE_COMPOSER_CONTROL_SIZE');
- expect(sendButtonDisabledStyle).toContain('backgroundColor: colors.surfaceChip');
- expect(sendButtonDisabledStyle).toContain('borderColor: colors.border');
- // 模型浮窗(ModelPickerSheet):composer 上方 drop-up 面板不回潮。2026-07-28 起
- // 权限从浮窗二级视图提为工具排独立药丸(permissionIndicator)+ 独立 sheet,
- // 新建页与会话页都隐藏浮窗 header 权限入口(hidePermissionTrigger),避免双入口;
- // 旧的 permissionButton/permissionPanel 形态仍不允许回潮。
- expect(newSource).toContain('<ModelPickerSheet');
- expect(newSource).toContain('testID="newSession.modelSheet"');
- expect(newSource).toContain('hidePermissionTrigger');
- expect(newSource).toContain('testID="newSession.permissionIndicator"');
- expect(newSource).toContain('testID="newSession.permissionSheet"');
- expect(newSource).not.toContain('testID="newSession.permissionButton"');
- expect(newSource).not.toContain('testID="newSession.permissionPanel"');
- expect(newSource).not.toContain('testID="newSession.modelPickerPanel"');
- // 语音生命周期内创建按钮常驻(2026-07-25 对齐桌面):录音中点创建=结束录音并
- // 用转写创建;否则首段转写落地瞬间按钮冒出来会把语音胶囊整格推左。
- expect(newSource).toContain("|| voiceStartPending\n || voiceState === 'listening'\n || voiceState === 'submitting'\n || voiceState === 'refining';");
- // listening 时只豁免「缺正文/附件」校验(路径/模型等其它校验不放行,
- // 否则按钮可点但必失败):点创建 = 停录并用最终转写创建(review 二轮收窄)。
- // 判定必须是结构化的 isNewSessionDraftMissingPayloadOnly,禁止比对本地化
- // 文案——locale 异步恢复时字符串比对会静默失效(review 三轮收口)。
- expect(newSource).toContain('isNewSessionDraftMissingPayloadOnly(draft, draftContent)');
- expect(newSource).not.toContain("=== t('session.new.enterFirstMessageOrAttachment')");
- expect(newSource).toContain('const canCreate = (!createValidation || (voiceIsListening && createValidationIsMissingPayload))');
- expect(newSource).not.toContain('(!createValidation || voiceIsListening) &&');
- expect(newSource).toContain('const composerShowCreateButton = composerHasMessage');
- expect(newSource).toContain('const deviceSelectorDisabled = creating || voiceIsProcessing || !deviceHasChoices;');
- // 按下即录(pressIn 起录):同一手势的松手由 voiceStartedOnPressInRef 吞掉,
- // 不再直接把 onPress 绑到 toggle。
- expect(voiceButtonSource).toContain('voiceStartedOnPressInRef.current = false;');
- expect(voiceButtonSource).toContain('toggleVoiceRecording();');
- expect(voiceButtonSource).toContain('disabled={creating || voiceIsProcessing}');
- expect(newSource).toContain('const startVoiceRecording = useCallback(async () => {');
- expect(newSource).toContain('const voiceStartupInFlightRef = useRef(false);');
- expect(newSource).toContain('const voicePermissionRequestInFlightRef = useRef(false);');
- expect(newSource).toContain('const voiceStopInFlightRef = useRef(false);');
- expect(newSource).toContain('if (!voiceRecordingActiveRef.current) {');
- expect(newSource).not.toContain('if (!voiceRecordingActiveRef.current && !voiceStopInFlightRef.current) {');
- expect(newSource).toContain('const voiceStartupSeqRef = useRef(0);');
- expect(newSource).toContain('|| voiceStopInFlightRef.current');
- expect(newSource).toContain('resolveMobileVoiceRecordingPermission({');
- expect(newSource).toContain('voiceStartupInFlightRef.current = true;');
- expect(newSource.indexOf('resolveMobileVoiceRecordingPermission({')).toBeLessThan(
- newSource.indexOf('voiceStartupInFlightRef.current = true;'),
- );
- expect(newSource).toContain('getPermission: getRecordingPermissionsAsync');
- expect(newSource).toContain("isAppActive: () => AppState.currentState === 'active'");
- expect(newSource).toContain(
- "voicePermissionRequestSeqRef.current !== permissionRequestSeq\n"
- + " || AppState.currentState !== 'active'\n"
- + " ) return;\n"
- + " startupSeq = voiceStartupSeqRef.current + 1;",
- );
- expect(newSource).toContain('const cancelVoiceForDeviceSwitch = useCallback(() => {');
- expect(selectDeviceSource).toContain('voicePermissionRequestInFlightRef.current');
- expect(selectDeviceSource).toContain('|| voiceStopInFlightRef.current');
- expect(selectDeviceSource).toContain('|| voiceIsProcessing');
- expect(selectDeviceSource).toContain('cancelVoiceForDeviceSwitch();');
- expect(newSource).toContain('voiceStartupInFlightRef.current = false;');
- expect(newSource).toContain('createMobileVoiceControllerSession({');
- expect(newSource).toContain('createMobileCindyVoiceCredential(selectedDeviceId)');
- expect(newSource).toContain('readNewSessionPreferences');
- expect(newSource).toContain('saveNewSessionPreferences');
- expect(newSource).toContain('pickNewSessionDefaultDevice({');
- expect(newSource).toContain('const userTouchedDeviceRef = useRef(false);');
- expect(newSource).toContain('if (!newSessionPreferencesLoaded) return;');
- expect(newSource).toContain('if (userTouchedDeviceRef.current) return;');
- expect(selectDeviceSource).toContain('userTouchedDeviceRef.current = true;');
- expect(selectWorkingDirSource).toContain('setShowHiddenDirectories(false);');
- expect(selectDialogueWorkspaceSource).toContain('setShowHiddenDirectories(false);');
- expect(selectRecentProjectSource).toContain('setShowHiddenDirectories(false);');
- expect(newSource).toContain("import { newSessionText } from '@/session/newSessionMessages';");
- expect(newSource).toContain('accessibilityRole="checkbox"');
- expect(newSource).toContain("accessibilityLabel={newSessionText('showHiddenDirectories')}");
- expect(newSource).toContain('accessibilityState={{ checked: showHiddenDirectories, disabled: creating || undefined }}');
- expect(newSource).toContain("{newSessionText('showHiddenDirectories')}");
- expect(newSource).toContain("{newSessionText('emptyDirectory')}");
- expect(newSource).not.toContain('显示隐藏文件夹');
- expect(newSource).not.toContain('没有可显示的子目录。');
- expect(browseHiddenToggleStyle).toContain('minHeight: 44');
- expect(storedAgentSource).toContain('if (selectedDeviceId) autoDefaultDeviceRef.current = selectedDeviceId;');
- expect(storedAgentSource).not.toContain('userTouchedRuntimeRef.current = true;');
- expect(newSource).toContain('void saveNewSessionPreferences({ agentKind: nextKind });');
- expect(newSource).toContain('testID="newSession.voiceStatus"');
- expect(newSource).toContain('testID="newSession.voiceSettingsButton"');
- expect(newSource).toContain('testID="newSession.voiceMicCaret"');
- expect(newSource).toContain("const renderComposerInputOverlay = () => voiceIsListening && Platform.OS !== 'ios' ? (");
- expect(newSource).toContain("import { buildSessionComposerLayout } from '@/session/sessionComposerLayout';");
- expect(newSource).toContain('const composerListeningPlaceholder = buildSessionComposerLayout({');
- expect(newSource).toContain('<Text style={styles.voiceDraftListeningText}>{composerListeningPlaceholder}</Text>');
- // 听写 mic 波形 caret 用正文色(对齐桌面 --chat-input-text,2026-07-28 用户定案),不用 statusReady 蓝绿。
- expect(newSource).toContain('<VoiceMicWaveCaret color={colors.textPrimary} testID="newSession.voiceMicCaret" />');
- // 语音态占位文案就是普通态 TextInput 的 placeholder,必须与 placeholderTextColor 同源,
- // 否则一进语音态这行字会变色(2026-07-31 用户定案:不再用 statusReady 蓝绿)。
- expect(newSource).toContain('placeholderTextColor={colors.textPlaceholder}');
- expect(newSource).toContain('voiceDraftListeningText: {\n color: colors.textPlaceholder,');
- expect(newSource).not.toContain('voiceDraftListeningText: {\n color: colors.statusReady,');
- expect(newSource).toContain('const voiceDraftShowsListeningPrompt = voiceIsListening && draft.firstMessage.length === 0;');
- expect(newSource).toContain('firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });');
- expect(newSource).toContain('voiceSelectionUserOwnedRef.current = false;\n voicePendingSelectionEchoesRef.current = [];\n const controller = createMobileVoiceControllerSession({');
- expect(newSource).toContain('voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });');
- expect(newSource).toContain('draft.firstMessage.slice(0, firstMessageSelectionRef.current.end)');
- expect(newSource).toContain('draft.firstMessage.slice(firstMessageSelectionRef.current.end)');
- expect(newSource).toContain('caret.measureLayout(block, (x, y) => {');
- expect(newSource).toContain('viewRef={voiceDraftCaretRef}');
- expect(sharedSource).toContain('export function VoiceMicWaveCaret');
- expect(newSource).toContain('const creatingRef = useRef(false);');
- expect(createSource).toContain('|| voiceStartupInFlightRef.current');
- expect(createSource).toContain('|| voiceStopInFlightRef.current');
- expect(createSource).toContain('|| voiceIsProcessing');
- expect(createSource).toContain('creatingRef.current = true;');
- expect(createSource.indexOf('creatingRef.current = true;')).toBeLessThan(createSource.indexOf('const latestDraftText = await finishVoiceRecording();'));
- expect(createSource).toContain('const latestDraftText = await finishVoiceRecording();');
- expect(createSource).toContain('effectiveDraft = { ...effectiveDraft, firstMessage: latestDraftText };');
- expect(createSource).toContain('creatingRef.current = false;');
- expect(createButtonSource).toContain('busy: creating');
- expect(createButtonSource).toContain('|| worktreeBranchPreferenceSaving');
- expect(newSource).toContain('disabled: !canCreate || undefined,');
- // No start cue on mobile: playing a cue via expo-audio during capture stalls
- // the AVAudioEngine record tap (see mobileVoiceCue.ts). Only the end cue is wired.
- expect(newSource).not.toContain('playMobileVoiceInputStartCue');
- expect(newSource).not.toContain('onReadyForStartCue');
- expect(newSource).toContain('onReadyForEndCue: credential.settings?.playInteractionSound ? playMobileVoiceInputEndCue : undefined,');
- // Touch-down warm-up: the mic button prewarms the audio session + ASR
- // connection at pressIn, and voice startup claims that connection when fresh.
- expect(newSource).toContain('onPressIn={handleVoiceButtonPressIn}');
- // 托管预热:凭登录态提前拿 voice-server 票据(BYOK/穿透路径已删除,
- // 手机语音只保留 Cindy 官方托管路径)。
- expect(newSource).toContain('prewarmMobileVoiceStart(selectedDeviceId, {');
- expect(newSource).toContain('getAccessToken: () => auth.getAccessToken(),');
- expect(newSource).toContain('refreshAccessToken: () => auth.refreshAccessToken(),');
- expect(newSource).toContain('apiFetch: auth.apiFetch,');
- expect(newSource).toContain('const prewarmedVoice = await (takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null));');
- // 语音历史与词典快照只服务润色提示:后台读取,不挡在开麦之前。
- expect(newSource).not.toContain('const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([');
- expect(newSource).toContain('void getMobileVoiceInputHistoryForHost(selectedDeviceId, prewarmedVoice?.credential.settings?.voiceInputHistory)');
- expect(newSource).toContain('localVoiceInputHistory: () => localVoiceInputHistory,');
- // 停止后 150ms 内保持录音胶囊,超过才显示处理转圈。
- expect(newSource).toContain('expanded: voiceIsListening || voiceStartPending || voiceProcessingIndicator.stopping,');
- // 停止期保持胶囊外观,只有与语音无关的禁用原因(创建中)才置灰。
- expect(newSource).toContain('(creating || (voiceIsProcessing && !voiceProcessingIndicator.stopping)) && styles.disabled,');
- expect(newSource).not.toContain('MobileVoiceServiceMode');
- expect(newSource).not.toContain('LiteLlm');
- expect(newSource).toContain('?? createMobileCindyVoiceCredential(selectedDeviceId);');
- expect(newSource).toContain('connectionProvider: (providerId: string) => voiceContext.createAsrConnection(providerId),');
- expect(newSource).toContain('voiceContext.createRefinerTarget(providerId, options),');
- expect(newSource).toContain('voiceContext.warmRefiner(input),');
- expect(newSource).toContain('const voiceUiAvailable = shouldShowMobileVoiceUi(Platform.OS);');
- expect(newSource).toContain('const composerVoicePlacement = voiceUiAvailable');
- expect(newSource).toContain('hasTrailingAction: composerShowCreateButton');
- expect(newSource).toContain('const voiceStatusVisible = voiceUiAvailable && Boolean(voiceError);');
- expect(newSource).toContain('floatingVoiceButton={voiceUiAvailable ? renderComposerVoiceButton : undefined}');
- expect(sessionSource).toContain('voicePlacement={composerVoicePlacement}');
- expect(sharedSource).toContain('export const MOBILE_COMPOSER_INPUT_MAX_VISIBLE_LINES = 12;');
- expect(sharedSource).toContain('MOBILE_COMPOSER_CONTROL_SIZE,');
- expect(sharedSource).toContain('resolveMobileComposerVoiceButtonPlacement,');
- expect(sharedSource).toContain('resolveMobileComposerVoiceButtonAnchorStyle({');
- expect(sharedSource).toContain('voicePlacement?.inline || voicePlacement?.floating');
- expect(sharedSource).not.toContain('styles.voiceButtonAnchor');
- expect(newSource).not.toContain('messageInput: {');
- expect(newSource).not.toContain('composerToolbar: {');
- expect(newSource).not.toContain('permissionIcon: {');
- expect(newSource).not.toContain('style={styles.messageInput}');
+ // Permission/async-start wiring stays a source guard: the production voice
+ // functions run in newSessionVoiceInput.test.tsx; the screen owns the OS
+ // foreground check and the create/recording interlock.
+ it('rechecks recording permission and foreground before starting or creating', () => {
+ const page = newSessionPageSource;
+ const permission = page.indexOf('resolveMobileVoiceRecordingPermission({');
+ const startup = page.indexOf('voiceStartupInFlightRef.current = true;', permission);
+ expect(permission).toBeGreaterThan(-1);
+ expect(startup).toBeGreaterThan(permission);
+ expect(page.slice(permission, startup)).toContain("AppState.currentState !== 'active'");
+ expect(page).toContain('getPermission: getRecordingPermissionsAsync');
+ const createStart = page.indexOf('const createMessageSession = useCallback');
+ const createEnd = page.indexOf('const createGoalSession = useCallback', createStart);
+ const create = page.slice(createStart, createEnd);
+ const claim = create.indexOf('creatingRef.current = true;');
+ const stop = create.indexOf('await finishVoiceRecording()');
+ expect(claim).toBeGreaterThan(-1);
+ expect(stop).toBeGreaterThan(claim);
+ expect(create).toContain('effectiveDraft = { ...effectiveDraft, firstMessage: latestDraftText };');
+ expect(create).toContain('creatingRef.current = false;');
});
});
@@ -2395,21 +2110,18 @@ describe('new session worktree wiring (source locks)', () => {
// - 失败(业务 {ok:false} / invoke 抛错)早退留在表单,不建会话。
const newSource = newSessionSources;
- it('runs worktree:create before the optimistic pipeline with the same preset sessionId', () => {
- const requestIdx = newSource.indexOf('const createRequest = buildWorktreeCreateRequest({');
- const createIdx = newSource.indexOf('await maker.worktree.create(createRequest)', requestIdx);
- const parseIdx = newSource.indexOf('parseWorktreeCreateResult(', requestIdx);
- const pipelineIdx = newSource.indexOf('startNewSessionCreation({');
- expect(requestIdx).toBeGreaterThan(0);
- expect(createIdx).toBeGreaterThan(0);
- expect(parseIdx).toBeGreaterThan(requestIdx);
- expect(pipelineIdx).toBeGreaterThan(createIdx);
- expect(newSource).toContain('effectiveDraft = { ...effectiveDraft, workingDir: resp.meta.path };');
- expect(newSource).toContain('setError(formatWorktreeCreateFailure(resp.error));');
- // 勾选生效三条件:project 模式 × 用户勾选 × 资格探测通过。
- expect(newSource).toContain('worktreeIntent.applicable');
- expect(newSource).toContain('&& worktreeIntent.enabled');
- expect(newSource).toContain("&& worktreeIntent.eligibility.status === 'eligible'");
+ // Persistence/reservation/path outcomes run through the real preparation in
+ // newSessionCreationPersistence.test.ts. This guard protects the remaining
+ // screen handoff, where starting early would bypass durable preparation.
+ it('awaits durable worktree preparation before handing its identity to the optimistic pipeline', () => {
+ const preparation = newSessionPageSource.indexOf('await prepareNewSessionCreation({');
+ const pipeline = newSessionPageSource.indexOf('startNewSessionCreation({', preparation);
+ expect(preparation).toBeGreaterThan(-1);
+ expect(pipeline).toBeGreaterThan(preparation);
+ const handoff = newSessionPageSource.slice(preparation, pipeline);
+ expect(handoff).toContain('if (!prepared) return;');
+ expect(handoff).toContain('effectiveDraft = prepared.effectiveDraft;');
+ expect(handoff).toMatch(/const \{ sessionId,[\s\S]*?\} = prepared;/);
});
it('re-probes worktree eligibility when the relay or workstation reconnects', () => {
@@ -2463,7 +2175,7 @@ describe('new session worktree wiring (source locks)', () => {
it('binds the new-screen recovery and background pipeline to the auth-owner generation', () => {
const ownerCapture = newSource.indexOf('const authOwnerAtCreate = getMobileAuthOwner();');
- const ownerCheck = newSource.indexOf('const isCurrentOwner = () => (', ownerCapture);
+ const ownerCheck = newSource.indexOf('captureNewSessionOwner(', ownerCapture);
const recovery = newSource.indexOf(
'const recovery = await recoverPendingPrecreatedWorktrees(worktreeAccountId, {',
ownerCheck,
@@ -2502,7 +2214,7 @@ describe('new session worktree wiring (source locks)', () => {
expect(failedPersistence).toBeGreaterThan(reservation);
expect(remoteCreate).toBeGreaterThan(failedPersistence);
expect(newSource.slice(failedPersistence, remoteCreate)).toContain(
- "setError(t('session.new.worktreeRecoveryStateFailed'))",
+ "setGoalError(t('session.new.worktreeRecoveryStateFailed'))",
);
expect(newSource.slice(remoteCreate, remoteCreate + 500)).toContain(
'recoveryKey,',
@@ -2511,7 +2223,7 @@ describe('new session worktree wiring (source locks)', () => {
'maker.worktree.discardPrecreated',
);
expect(newSource.slice(remoteCreate, remoteCreate + 2_500)).toContain(
- "setError(t('session.new.worktreeCleanupPending'))",
+ "setGoalError(t('session.new.worktreeCleanupPending'))",
);
});
@@ -2523,7 +2235,7 @@ describe('new session worktree wiring (source locks)', () => {
expect(newSource).toContain('worktreeSourceBranchFromPreference(');
expect(newSource).toContain('shouldAcceptWorktreeBranchListResult({');
expect(newSource).toContain('sourceBranch: worktreeIntent.sourceBranch,');
- expect(newSource).toContain('const worktreeIntent = captureWorktreeCreateIntent();');
+ expect(newSource).toContain('const worktreeIntent = prepareWorktreeCreateIntent(');
expect(newSource).toContain('isWorktreeCreateIntentCurrent(worktreeIntent)');
expect(newSource).toContain('precreatedWorktree = {');
expect(newSource).toContain('recoveryKey,');
@@ -2538,7 +2250,7 @@ describe('new session worktree wiring (source locks)', () => {
expect(newSource.slice(disabledStart, disabledEnd + 1)).not.toContain('worktreeEnabled');
const selectStart = newSource.indexOf('const selectWorktreeSourceBranch = useCallback(');
- const selectEnd = newSource.indexOf('// —— worktree 勾选播种', selectStart);
+ const selectEnd = newSource.indexOf('\n }, [', selectStart);
const selectBlock = newSource.slice(selectStart, selectEnd);
expect(selectBlock).toContain('maker.applyNewMakerWorktreeBranchPref(');
expect(selectBlock).not.toContain('toggleWorktree');
@@ -2653,7 +2365,7 @@ describe('submit guard catalog wiring (source locks)', () => {
expect(createStart).toBeGreaterThan(-1);
expect(goalStart).toBeGreaterThan(createStart);
const createSlice = newSource.slice(createStart, goalStart);
- const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
+ const goalSlice = newSessionPageSource.slice(newSessionPageSource.indexOf('const createGoalSession = useCallback'), newSessionPageSource.indexOf('const create = useCallback'));
// 入口设备检查先于加锁(round-20 Standards P1 busy 泄漏):goal 的 setGoalBusy(true)
// 前必须有该 return(create() 的检查在 try 内,finally 兜底,不要求此序)。
// Standards P1:先断言 needle 存在(indexOf=-1 会让 -1<X 假通过)。
@@ -2785,7 +2497,8 @@ describe('submit guard catalog wiring (source locks)', () => {
// resolveStartedDowngradeOrCommit 的降级/恢复 await 窗口可能换代(来源恢复或
// 替换为 B)——鉴权降级失败(commit)分支必须像设备切换 commit 分支一样重跑
// 有界 runGuard + genAt 核对,否则用等待前的空/旧目录校准草稿(codex review P2)。
- const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
+ const goalStart = newSessionPageSource.indexOf('const createGoalSession = useCallback');
+ const goalSlice = newSessionPageSource.slice(goalStart, newSessionPageSource.indexOf('const create = useCallback', goalStart));
// 两处 commit 后的 re-fence(鉴权降级 + 设备切换)
const reFences = goalSlice.match(/for \(let pass = 0; pass < 2; pass \+= 1\) \{\s*\n\s*guardResult = await runGuard\(\);/g) ?? [];
expect(reFences.length).toBe(2);
@@ -2808,7 +2521,8 @@ describe('submit guard catalog wiring (source locks)', () => {
});
it('goal commit segment: started 后无裸 return,goal.set 先于本地同步(round-22 Spec P1-2/P1-3)', () => {
- const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
+ const goalStart = newSessionPageSource.indexOf('const createGoalSession = useCallback');
+ const goalSlice = newSessionPageSource.slice(goalStart, newSessionPageSource.indexOf('const create = useCallback', goalStart));
const iStarted = goalSlice.indexOf('sessionCreateStarted = true;');
const iCreate = goalSlice.indexOf('maker.createSession(');
expect(iStarted).toBeGreaterThan(0);
@@ -2840,7 +2554,8 @@ describe('submit guard catalog wiring (source locks)', () => {
// goal.set 等待期间同账号可能切换设备:owner 检查拦不住,settle 若继续用旧
// selectedDeviceId 会把设备 A 的会话写进当前页面并跳转设备 A 会话页,用户
// 还会在设备 B 上重复创建——settle 每处中止必须并列设备复核(greptile P1)。
- const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
+ const goalStart = newSessionPageSource.indexOf('const createGoalSession = useCallback');
+ const goalSlice = newSessionPageSource.slice(goalStart, newSessionPageSource.indexOf('const create = useCallback', goalStart));
const settleStart = goalSlice.indexOf('── settle 段');
expect(settleStart).toBeGreaterThan(0);
const settleSlice = goalSlice.slice(settleStart, goalSlice.indexOf('router.replace({'));
@@ -2856,7 +2571,8 @@ describe('submit guard catalog wiring (source locks)', () => {
});
it('goal settle 只登记本机预览,不把目标文案写成用户改名', () => {
- const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
+ const goalStart = newSessionPageSource.indexOf('const createGoalSession = useCallback');
+ const goalSlice = newSessionPageSource.slice(goalStart, newSessionPageSource.indexOf('const create = useCallback', goalStart));
const settleSlice = goalSlice.slice(
goalSlice.indexOf('── settle 段'),
goalSlice.indexOf('router.replace({'),
@@ -2888,18 +2604,6 @@ describe('fast memory restore wiring (source locks)', () => {
// PR #6559 P1: replace the boolean-only source assertion with the production
// effect's draft output. Unit tier; no React Native mount or real waiting.
- const effectStart = newSource.indexOf(' useEffect(() => {', newSource.indexOf(' // Fast 记忆延迟恢复'));
- const effectJs = ts.transpileModule(newSource.slice(effectStart, newSource.indexOf(' // 拉被控端 runtime', effectStart)), {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
- }).outputText;
- const runRestoreEffect = new Function('env', `
- const {selectedDeviceId, draft, draftMemory, modelRowsRef, activeSourceIdRef,
- catalogReadyRef, targetAgentHasFast, getCachedAgentCapabilities,
- buildAgentCapabilitiesCacheKey, setDraft, capabilities, modelRows,
- deviceProviders, isFastRestorable} = env;
- const useEffect = fn => fn();
- ${effectJs}
- `);
it('defers speed restoration until capabilities arrive and clears a revoked Ultrafast tier', () => {
const rows = flattenProviderSections(buildMobileModelSections({
@@ -2911,17 +2615,14 @@ describe('fast memory restore wiring (source locks)', () => {
efforts: [], defaultEffort: null, supportsFastMode: true, supportsUltrafastMode: true }] },
}],
}).sections);
- let draft = { agentKind: 'codex' as const, model: 'gpt', providerId: 'openai', fastMode: false as boolean | 'ultrafast' };
+ let draft = newSessionDraft({ agentKind: 'codex', model: 'gpt', providerId: 'openai', fastMode: false });
let capsKnown = false;
let remembered: boolean | 'ultrafast' = 'ultrafast';
- const restore = () => runRestoreEffect({
+ const restore = () => restoreNewSessionFastPreference({
selectedDeviceId: 'host', draft, draftMemory: { getFast: () => remembered },
- modelRowsRef: { current: rows }, activeSourceIdRef: { current: 'openai' },
- catalogReadyRef: { current: true }, targetAgentHasFast: () => capsKnown,
- getCachedAgentCapabilities: () => capsKnown ? {} : undefined,
- buildAgentCapabilitiesCacheKey: () => 'host:codex',
- setDraft: (update: (current: typeof draft) => typeof draft) => { draft = update(draft); },
- capabilities: null, modelRows: rows, deviceProviders: { ready: true }, isFastRestorable,
+ modelRows: rows, activeSourceId: 'openai', catalogReady: true,
+ hasFast: () => capsKnown, capabilitiesKnown: capsKnown,
+ setDraft: update => { draft = typeof update === 'function' ? update(draft) : update; },
});
restore();
expect(draft.fastMode).toBe(false);
@@ -3125,53 +2826,6 @@ describe('closed saved model requires reselection', () => {
// unit:执行页面原始回调与生产解析函数(不复制逻辑、不扫描参数字符串),断言最终计费来源。
// 原 Hook 用例没有覆盖 app/ 的接线;旧号池或 xd 无模型行,自定义来源与新号池同名且排在前。
describe('页面 Auto 校准和提交保留 Cindy 来源身份', () => {
- const pageSource = ts.createSourceFile(
- 'new.tsx',
- readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TSX,
- );
- const callbacks: ts.ArrowFunction[] = [];
- function visit(node: ts.Node) {
- if (
- ts.isCallExpression(node) &&
- ts.isIdentifier(node.expression) &&
- node.expression.text === 'resolveRecentModelAndProvider'
- ) {
- let parent: ts.Node | undefined = node.parent;
- while (parent && !ts.isArrowFunction(parent)) parent = parent.parent;
- if (!parent || !ts.isArrowFunction(parent))
- throw new Error('Missing page reconciliation callback');
- callbacks.push(parent);
- }
- ts.forEachChild(node, visit);
- }
- visit(pageSource);
- if (callbacks.length !== 4) throw new Error('Update Auto entry coverage after page refactor');
- const entryNames = ['目录校准', '普通提交终检', '鉴权后终检', '目标模式终检'];
- const entries = callbacks.map((callback, index) => {
- const compiled = ts.transpileModule(
- `async function run(bindings) {
- let { effectiveDraft } = bindings;
- const { modelRows, deviceProviders, rows, resolveRecentModelAndProvider,
- modelNeedsReselection, assertSubmitModelResolved, reconcileEffortAfterFallback,
- isCindyAutoModelId, buildMobileModelSections, flattenProviderSections } = bindings;
- const guardSelected = () => ({ model: effectiveDraft.model, providerId: effectiveDraft.providerId });
- const apply = ${callback.getText(pageSource)};
- const result = await apply(bindings.argument);
- return result ?? effectiveDraft;
- }`,
- { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
- ).outputText;
- return {
- name: entryNames[index],
- index,
- run: new Function(`${compiled}; return run;`)() as (
- bindings: Record<string, unknown>,
- ) => Promise<{ model: string; providerId: string | null }>,
- };
- });
const auto = 'auto/group-1';
const provider = (id: string, source: 'builtin' | 'organization' | 'user', ids: string[]) =>
({
@@ -3209,36 +2863,25 @@ describe('页面 Auto 校准和提交保留 Cindy 来源身份', () => {
},
}));
const fresh = { providers };
+ const entries = [
+ { name: '目录校准', run: (draft: NewSessionDraft, _guard: SubmitGuardCatalog) =>
+ reconcileNewSessionCatalogDraft(draft, rows, fresh) },
+ { name: '普通/目标提交终检', run: (draft: NewSessionDraft, guard: SubmitGuardCatalog) =>
+ reconcileNewSessionSubmitDraft(draft, guard, () => false, key => key) },
+ { name: '鉴权后终检', run: (draft: NewSessionDraft, _guard: SubmitGuardCatalog) =>
+ revalidateNewSessionDraftAfterAuth(draft, fresh, () => false, key => key) },
+ ];
it.each(entries.flatMap((entry) => ['pool-old', null].map((from) => ({ ...entry, from }))))(
'$name:$from 搬到新号池,不采用排在前面的自定义来源',
- async ({ index, run, from }) => {
- const draft = {
- ...DEFAULT_NEW_SESSION_DRAFT,
- agentKind: 'pi',
- model: auto,
- providerId: from,
- fastMode: false,
- };
+ async ({ run, from }) => {
+ const draft = newSessionDraft({ agentKind: 'pi', model: auto, providerId: from, fastMode: false });
const guard = await resolveSubmitGuardCatalog({
cached: () => undefined,
gen: () => 0,
fetch: async () => fresh,
buildRows: () => rows,
});
- const result = await run({
- effectiveDraft: draft,
- modelRows: rows,
- rows,
- deviceProviders: fresh,
- argument: index === 0 ? draft : index === 2 ? fresh : guard,
- resolveRecentModelAndProvider,
- modelNeedsReselection,
- isCindyAutoModelId,
- buildMobileModelSections,
- flattenProviderSections,
- assertSubmitModelResolved,
- reconcileEffortAfterFallback,
- });
+ const result = await run(draft, guard);
expect(result).toMatchObject({ model: auto, providerId: 'pool-new' });
},
);
diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.ts
index 2cfc20f07a..5073bc93ca 100644
--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts
@@ -8,14 +8,11 @@
* - retry(同 id 幂等)与 dismiss(返回编辑)收口。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import type { RemoteSerializedAttachment } from '@/session/types';
-import { createDurableOutbox, isDurableOutboxHandedOff, isDurableOutboxSettled, type DurableOutboxRecord } from '@/session/durableOutbox';
-import { buildOutboxItem, outboxItemAttachments } from '@/session/sessionOutbox';
-import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
+import { createDurableOutbox, type DurableOutboxRecord } from '@/session/durableOutbox';
+import { buildOutboxItem } from '@/session/sessionOutbox';
+import { createOutboxMessageLeases, outboxNeedsReconciliation, outboxSessionIsHidden } from '@/session/mobileOutboxSessionAdapter';
const recoveryStorage = vi.hoisted(() => new Map<string, string>());
const persistCancelledDraft = vi.hoisted(() => vi.fn(async () => {}));
@@ -86,50 +83,21 @@ const DRAFT: NewSessionDraft = {
firstMessage: 'hello world',
};
-// Execute the bridge's actual refresh callback with the real session store.
-// This includes hydration, cancellation cleanup and message-work lease release.
-const bridgeSource = ts.createSourceFile('MobileOutboxBridge.tsx', readFileSync(resolve(
- process.cwd(), 'src/session/MobileOutboxBridge.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let refreshSource = '';
-let reconciliationSource = '';
-let knownSessionSource = '';
-let hiddenSource = '';
-function findRefresh(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && node.name.getText(bridgeSource) === 'knownSession') {
- knownSessionSource = node.initializer!.getText(bridgeSource);
- }
- if (ts.isVariableDeclaration(node) && node.name.getText(bridgeSource) === 'hidden') {
- hiddenSource = node.initializer!.getText(bridgeSource);
- }
- if (ts.isVariableDeclaration(node) && node.name.getText(bridgeSource) === 'refreshLeases') {
- refreshSource = node.initializer!.getText(bridgeSource);
- }
- if (ts.isVariableDeclaration(node) && node.name.getText(bridgeSource) === 'needsReconciliation') {
- reconciliationSource = node.initializer!.getText(bridgeSource);
- }
- ts.forEachChild(node, findRefresh);
-}
-findRefresh(bridgeSource);
-if (!refreshSource) throw new Error('Missing outbox lease refresh callback');
+// Exercise the production lease manager with the real session store, including
+// hydration, cancellation cleanup and message-work lease release.
function outboxLeaseHarness(initial: DurableOutboxRecord[]) {
let records = initial;
const visible = new Set<string>();
- const leases = new Map<string, ReturnType<typeof remoteSessionStore.acquireSessionMessageWork>>();
- const bindings = { isCurrent: () => true, mobileDurableOutbox: { getSnapshot: () => records },
- isDurableOutboxHandedOff, isDurableOutboxSettled, remoteSessionStore, sessionFromCreateResult, outboxItemAttachments,
- CINDY_MAKE_ENABLED, isCindyMakeSource,
- findRemoteHistoryView: (_deviceId: string, sessionId: string) => ({ isActive: () => visible.has(sessionId) }),
- dismissRecoveredPrecreatedSession, restoreNewSessionDurableEdit, leases,
- leaseKey: (record: DurableOutboxRecord) => JSON.stringify([record.deviceId, record.item.sessionId]) };
- const compiled = ts.transpileModule(`function create(bindings) {
- const { ${Object.keys(bindings).join(', ')} } = bindings;
- const needsReconciliation = ${reconciliationSource};
- const knownSession = ${knownSessionSource};
- const hidden = ${hiddenSource};
- return ${refreshSource};
- }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const create = new Function(`${compiled}; return create;`)() as (values: typeof bindings) => () => void;
- return { refresh: create(bindings), leases, visible, setRecords: (next: DurableOutboxRecord[]) => { records = next; } };
+ const manager = createOutboxMessageLeases({
+ isCurrent: () => true,
+ getRecords: () => records,
+ hidden: record => outboxSessionIsHidden(record, remoteSessionStore.getSessions()),
+ needsReconciliation: record => outboxNeedsReconciliation(record, visible.has(record.item.sessionId)),
+ restoreEditable: restoreNewSessionDurableEdit,
+ dismissCancelled: dismissRecoveredPrecreatedSession,
+ store: remoteSessionStore,
+ });
+ return { ...manager, visible, setRecords: (next: DurableOutboxRecord[]) => { records = next; } };
}
function recoveryOutboxRecord(sessionId: string): DurableOutboxRecord {
return { version: 1, accountId: 'owner-a', deviceId: 'dev-1', createdAt: 1, state: 'failed', uploads: [],
diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
index 0bed19146c..f4a5a0ac0b 100644
--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
@@ -1,9 +1,11 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
+import type { Dispatch, SetStateAction } from 'react';
+import { prepareNewSessionCreation, newSessionCreationPreparationServices } from '@/session/prepareNewSessionCreation';
+import type { NewSessionDraft } from '@/session/newSession';
+import type { WorktreeCreateRequest } from '@/session/newSessionWorktree';
+import { newSessionAttachment, newSessionDraft } from './fixtures/newSession';
import { beforeEach, expect, it, vi } from 'vitest';
import { getMobileAuthOwner, setMobileAuthOwner } from '../auth/authOwnerGeneration';
-import type { MobileMakerTransport } from '../device-link/mobileMakerTransport';
+import type { MobileMakerTransport, MobileWorktreeCreateResult } from '../device-link/mobileMakerTransport';
import type { DurableOutboxRecord } from '../session/durableOutbox';
import type { MobileLocalAttachmentUploadCandidate } from '../session/mobileLocalAttachmentUpload';
import { retainOutboxFile, durableOutboxUploadUri, removeRetainedOutboxFiles } from '../session/durableOutboxFiles';
@@ -55,26 +57,13 @@ import { listPendingPrecreatedWorktrees, recoverPendingPrecreatedWorktrees, regi
import { completePrecreatedWorktreeRecovery } from '../session/completePrecreatedWorktreeRecovery';
import { appendNewSessionEditComposer, findNewSessionEditDraft, withNewSessionCreationRemoval } from '../session/newSessionCreation';
-// Run the page's actual recovery -> durable save -> worktree creation statements.
-// Extract AST nodes, as in newSessionWorktreeSync, so ordering is tested without
-// duplicating the production pipeline or mounting unrelated native UI modules.
-const source = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),
- ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let statements: readonly ts.Statement[] | undefined;
-function visit(node: ts.Node) {
- if (ts.isBlock(node) && node.statements.some((s) => ts.isVariableStatement(s)
- && s.declarationList.declarations.some((d) => d.name.getText(source) === 'previousRecovery'))) {
- const start = node.statements.findIndex((s) => ts.isVariableStatement(s)
- && s.declarationList.declarations.some((d) => d.name.getText(source) === 'previousRecovery'));
- const end = node.statements.findIndex((s) => ts.isBlock(s)
- && s.getText(source).includes('resolveSubmitGuardCatalog'));
- if (end < start) throw new Error('Missing page creation persistence boundary');
- statements = node.statements.slice(start, end);
- }
- ts.forEachChild(node, visit);
+// Unit: call the production submission boundary with real durable storage and file retention.
+// Creation-recovery rules require bytes to survive reservation failures, lost replies,
+// deletion and resubmission; source fragments previously hid parser and type mismatches.
+function worktreeCreatedResult(request: WorktreeCreateRequest): MobileWorktreeCreateResult {
+ return { ok: true, meta: { ...request, path: '/repo/.cindy-worktrees/new', branch: 'cindy/new',
+ createdAt: '2026-10-23T00:00:00.000Z' } };
}
-visit(source);
-if (!statements) throw new Error('Missing page creation pipeline');
beforeEach(async () => {
setMobileAuthOwner(null);
@@ -93,46 +82,47 @@ beforeEach(async () => {
function harness(previous: DurableOutboxRecord | null = null) {
let sequence = 0;
- const draft = { agentKind: 'codex', workspaceKind: 'project', workingDir: '/repo', model: 'model',
- providerId: null, effort: 'high', permissionMode: 'ask', fastMode: false, firstMessage: 'keep my input' };
+ const draft = newSessionDraft({ agentKind: 'codex', workspaceKind: 'project', workingDir: '/repo', model: 'model',
+ providerId: null, effort: 'high', permissionMode: 'ask', fastMode: false, firstMessage: 'keep my input' });
const bindings = {
effectiveDraft: { ...draft, ...previous?.creation?.draft },
outboxRecoveryRef: { current: previous },
getCurrentMobileOutboxRecords, mobileDurableOutbox, outboxCreationRetryIdentity, buildOutboxItem,
selectedDeviceId: 'pc', selectedDeviceName: 'PC', authOwnerAtCreate: getMobileAuthOwner(),
worktreeAccountId: 'alice', creatingWorktree: true,
- worktreeIntent: { applicable: true, enabled: true, eligibility: { status: 'eligible', baseRepo: '/repo' }, sourceBranch: 'main' },
+ worktreeIntent: { applicable: true, enabled: true, eligibility: { status: 'eligible' as const, baseRepo: '/repo', sourceBranch: 'main' }, sourceBranch: 'main',
+ target: { deviceId: 'pc', workingDir: '/repo' }, branchPreferenceKey: 'pc/repo', branchPreferenceSyncKey: 'generation' },
isCurrentOwner: () => true, ensureDeviceAlive: () => true, isWorktreeCreateIntentCurrent: () => true,
createNewSessionId: () => `session-${++sequence}`, createOutboxClientId: () => 'message',
runtimeOptions: { permissionOptions: [] }, prePlanPermissionModeRef: { current: null },
planModeCapability: false, planModeDraftOn: false,
holdNewSessionCreationDraft, holdPrecreatedWorktreeRegistration: () => () => {},
- sendAttachments: [{ id: 'photo', path: 'oss://photo', name: 'photo.png', ext: 'png', size: 3, category: 'image', mimeType: 'image/png' }],
+ sendAttachments: [newSessionAttachment()],
attachmentPreviews: {}, getUploadedSource: (_id: string): MobileLocalAttachmentUploadCandidate | undefined => ({ uri: 'file:///photo.png', name: 'photo.png', size: 3, kind: 'image' }),
persistNewSessionCreationDraft,
removeRetainedOutboxFiles, releaseUploadedSources: vi.fn(),
outboxAttachmentNeedsLocalBytes: () => true,
registerPendingPrecreatedWorktree: vi.fn(async (..._args: Parameters<typeof registerPendingPrecreatedWorktree>) => true), forgetPendingPrecreatedWorktree: vi.fn(),
- buildWorktreeCreateRequest: (input: unknown) => input,
- parseWorktreeCreateResult: (input: unknown) => input,
maker: { getSession: vi.fn(async () => null), worktree: {
suggestName: vi.fn(async () => ({ name: 'new' })),
- create: vi.fn(async (): Promise<unknown> => ({ ok: true, meta: { path: '/repo/.cindy-worktrees/new' } })),
+ create: vi.fn(async (request: WorktreeCreateRequest): Promise<MobileWorktreeCreateResult> => worktreeCreatedResult(request)),
+ discardPrecreated: vi.fn(async () => ({ discarded: true as const })),
} },
- t: (key: string) => key, setError: vi.fn(), setDraft: vi.fn(),
- formatRemoteError: (error: Error) => error.message,
- formatWorktreeCreateFailure: () => 'worktree failed',
+ t: (key: string) => key, setError: vi.fn(), setDraft: vi.fn<Dispatch<SetStateAction<NewSessionDraft>>>(),
+ resolveWorktreeCreateErrorKey: () => 'session.new.worktreeDetectFailed',
};
- const compiled = ts.transpileModule(`async function run(bindings) {
- let { ${Object.keys(bindings).join(', ')} } = bindings;
- let releaseDurableCreation, releasePrecreatedRegistration;
+ const run = async () => {
+ const releases: Array<() => void> = [];
try {
- ${statements!.map((node) => node.getText(source)).join('\n')}
- return { effectiveDraft, sessionId };
- } finally { releaseDurableCreation?.(); releasePrecreatedRegistration?.(); }
- }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const run = new Function(`${compiled}; return run;`)() as (input: typeof bindings) => Promise<unknown>;
- return { bindings, run: () => run(bindings) };
+ return await prepareNewSessionCreation({
+ ...bindings, onHoldDurableCreation: release => releases.push(release),
+ onHoldPrecreatedRegistration: release => releases.push(release),
+ }, { ...newSessionCreationPreparationServices, ...bindings });
+ } finally {
+ for (const release of releases.reverse()) release();
+ }
+ };
+ return { bindings, run };
}
it.each(['reservation-fails', 'create-rejected', 'reply-lost', 'leaves-during-create'] as const)(
@@ -146,7 +136,7 @@ it.each(['reservation-fails', 'create-rejected', 'reply-lost', 'leaves-during-cr
h.bindings.createNewSessionId = () => 'replacement-session';
h.bindings.effectiveDraft.firstMessage = 'updated input before retry';
if (scenario === 'reservation-fails') h.bindings.registerPendingPrecreatedWorktree.mockResolvedValueOnce(false);
- else if (scenario === 'create-rejected') h.bindings.maker.worktree.create.mockResolvedValueOnce({ ok: false, error: {} });
+ else if (scenario === 'create-rejected') h.bindings.maker.worktree.create.mockResolvedValueOnce({ ok: false, error: { kind: 'failure', message: 'worktree failed' } });
else if (scenario === 'reply-lost') {
h.bindings.registerPendingPrecreatedWorktree.mockImplementation(registerPendingPrecreatedWorktree);
h.bindings.maker.worktree.create.mockRejectedValueOnce(new Error('reply lost'));
@@ -156,7 +146,7 @@ it.each(['reservation-fails', 'create-rejected', 'reply-lost', 'leaves-during-cr
expect(getNewSessionCreationTask('replacement-session')).toBeNull();
expect(hasLiveNewSessionCreation('replacement-session')).toBe(true);
expect(remoteSessionStore.getSessions()).toEqual([]);
- return { ok: false, error: {} };
+ return { ok: false, error: { kind: 'failure', message: 'worktree failed' } };
});
}
await h.run();
@@ -311,9 +301,9 @@ it('does not reserve or dispatch a worktree if saving its draft fails', async ()
it('keeps the original durable input when patching the successful worktree path fails', async () => {
const h = harness();
- h.bindings.maker.worktree.create.mockImplementationOnce(async () => {
+ h.bindings.maker.worktree.create.mockImplementationOnce(async (request) => {
disk.fail = true;
- return { ok: true, meta: { path: '/repo/.cindy-worktrees/new' } };
+ return worktreeCreatedResult(request);
});
await expect(h.run()).rejects.toThrow('disk unavailable');
disk.fail = false;
@@ -334,7 +324,8 @@ it.each([true, false])('reprobes a restored directory instead of submitting old
h.bindings.creatingWorktree = false;
expect(await h.run()).toBeUndefined();
expect(h.bindings.setDraft).toHaveBeenCalledOnce();
- const restored = h.bindings.setDraft.mock.calls[0][0](h.bindings.effectiveDraft);
+ const update = h.bindings.setDraft.mock.calls[0][0];
+ const restored = typeof update === 'function' ? update(h.bindings.effectiveDraft) : update;
expect(restored).toMatchObject({ workingDir: '/repo', firstMessage: 'keep my input' });
expect(h.bindings.maker.getSession).not.toHaveBeenCalled();
expect(h.bindings.maker.worktree.create).not.toHaveBeenCalled();
@@ -408,7 +399,7 @@ it('preserves a directory explicitly selected by the user while cancellation com
await h.run();
expect(h.bindings.setDraft).not.toHaveBeenCalled();
expect(h.bindings.maker.worktree.create).toHaveBeenCalledWith(expect.objectContaining({
- eligibility: expect.objectContaining({ baseRepo: '/other-repo' }),
+ baseRepo: '/other-repo',
}));
expect(getCurrentMobileOutboxRecords()[0].creation?.originalWorkingDir).toBe('/other-repo');
});
diff --git a/apps/mobile/src/__tests__/newSessionDraftRecovery.test.ts b/apps/mobile/src/__tests__/newSessionDraftRecovery.test.ts
index 03578bb8c5..5732e81e94 100644
--- a/apps/mobile/src/__tests__/newSessionDraftRecovery.test.ts
+++ b/apps/mobile/src/__tests__/newSessionDraftRecovery.test.ts
@@ -1,20 +1,13 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
+import { restoreNewSessionDraft } from '@/session/newSessionForm';
+import type { RemoteSerializedAttachment } from '@/session/types';
+import { newSessionAttachment } from './fixtures/newSession';
import { expect, it, vi } from 'vitest';
import { DEFAULT_NEW_SESSION_DRAFT } from '../session/newSession';
-// Exercise the actual screen callback without loading native UI modules.
-const source = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+// Unit: restore the production form boundary; recovered text, Plan and remote Agent
+// must be available before the next composer event (mobile-development: creation recovery).
function fixture() {
- let expression: ts.Expression | undefined;
- const visit = (node: ts.Node) => {
- if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'restoreCreationDraft') expression = node.initializer;
- ts.forEachChild(node, visit);
- };
- visit(source);
- if (!expression) throw new Error('Missing draft recovery callback');
- const state = { draft: { ...DEFAULT_NEW_SESSION_DRAFT }, selection: { start: 0, end: 0 }, plan: false, files: [] as unknown[] };
+ const state = { draft: { ...DEFAULT_NEW_SESSION_DRAFT }, selection: { start: 0, end: 0 }, plan: false, files: [] as RemoteSerializedAttachment[] };
const bindings = {
useCallback: (fn: unknown) => fn,
userTouchedWorkspaceRef: { current: false }, userTouchedRuntimeRef: { current: false },
@@ -22,20 +15,20 @@ function fixture() {
firstMessageRef: { current: '' }, firstMessageSelectionRef: { current: state.selection },
attachmentsRef: { current: state.files }, prePlanPermissionModeRef: { current: null as string | null },
setFirstMessageSelection: (value: typeof state.selection) => { state.selection = value; },
- setAttachments: (value: unknown[]) => { state.files = value; },
+ setAttachments: (value: RemoteSerializedAttachment[]) => { state.files = value; },
setPlanModeDraftOn: (value: boolean) => { state.plan = value; },
setDraft: vi.fn((value: typeof state.draft) => { state.draft = value; }),
setRemoteAgentChoice: vi.fn(),
};
- const compiled = ts.transpileModule(`const apply = ${expression.getText(source)};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const apply = new Function(...Object.keys(bindings), `${compiled}\nreturn apply;`)(...Object.values(bindings));
+ const apply = (...args: Parameters<typeof restoreNewSessionDraft> extends [unknown, ...infer Rest] ? Rest : never) =>
+ restoreNewSessionDraft(bindings, ...args);
return { ...bindings, state, apply };
}
it.each([true, false])('restores Plan=%s and makes recovered text immediately available to composer actions', (enabled) => {
const f = fixture();
const draft = { ...DEFAULT_NEW_SESSION_DRAFT, firstMessage: 'Recovered message', model: 'saved-model', permissionMode: 'ask' };
- const files = [{ id: 'saved-file' }];
+ const files = [newSessionAttachment({ id: 'saved-file' })];
f.apply(draft, files, { enabled, restorePermissionMode: 'ask' });
// Slash/mention/voice actions read these refs before another text-change event.
const caret = f.firstMessageSelectionRef.current.end;
diff --git a/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts b/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts
index fa87d78e62..aaeadd8ef2 100644
--- a/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts
+++ b/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts
@@ -1,94 +1,58 @@
-// Execute the real page callback: shares can upload before a computer is chosen.
-// First/same-host selection must preserve them; a real host switch still discards.
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
import { expect, it, vi } from 'vitest';
+import { appendNewSessionSharedText, openNewSessionPluginPalette, patchNewSessionDraft } from '@/session/newSessionForm';
+import { clearNewSessionAttachmentsForDeviceChange } from '@/session/newSessionAttachmentCleanup';
+import { newSessionAttachment, newSessionDraft } from './fixtures/newSession';
+import type { NewSessionDraft } from '@/session/newSession';
+import type { RemoteSerializedAttachment } from '@/session/types';
-const page = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),
- ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let callback: ts.ArrowFunction | undefined;
-function visit(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && node.name.getText(page) === 'selectDevice'
- && node.initializer && ts.isCallExpression(node.initializer)) {
- const first = node.initializer.arguments[0];
- if (first && ts.isArrowFunction(first)) callback = first;
- }
- ts.forEachChild(node, visit);
-}
-visit(page);
-if (!callback) throw new Error('Missing actual new-task device selection callback');
-const setterNames = [...new Set(callback.getText(page).match(/\bset[A-Z]\w*/g) ?? [])];
-const compiled = ts.transpileModule(`const selectDevice = ${callback.getText(page)};`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None, alwaysStrict: false },
-}).outputText;
-function run(bindings: Record<string, unknown>) {
- const select = new Function(...Object.keys(bindings), `${compiled}; return selectDevice;`)(...Object.values(bindings));
- select({ deviceId: 'new-host', name: 'Fixture' });
-}
+// Unit: a share may finish uploading before the first computer is selected.
+// Preserve those bytes on initial/same-host selection, discard only on a real switch.
+const discard = vi.hoisted(() => vi.fn());
+vi.mock('@/session/mobileAttachmentUpload', () => ({ discardMobileUploadedAttachment: discard }));
it.each([['', false], ['new-host', false], ['old-host', true]] as const)(
- 'preserves initial shares with previous host %s (discard=%s)', (previous, discard) => {
- const bindings: Record<string, unknown> = {
- creating: false, voiceIsProcessing: false, voiceState: 'idle',
- attachments: [{ id: 'shared-attachment' }], auth: { getAccessToken: vi.fn() },
- selectedDeviceIdRef: { current: previous }, browseSeqRef: { current: 0 },
- composerAnnotationsRef: { current: { forgetAllAttachments: vi.fn() } },
- };
- for (const name of ['voicePermissionRequestInFlightRef', 'voiceStopInFlightRef', 'voiceStartupInFlightRef',
- 'voiceRecordingActiveRef', 'userTouchedDeviceRef', 'userTouchedRuntimeRef']) bindings[name] = { current: false };
- for (const name of ['explicitProviderModelSelectionRef', 'autoDefaultDeviceRef', 'initialWorkspaceKeyRef']) bindings[name] = { current: null };
- for (const name of ['cancelVoiceForDeviceSwitch', 'saveNewSessionPreferences', 'discardMobileUploadedAttachment',
- 'discardAllPendingUploads', 'releaseUploadedSources']) bindings[name] = vi.fn();
- for (const name of setterNames) bindings[name] = vi.fn();
- run(bindings);
- expect(bindings.discardMobileUploadedAttachment).toHaveBeenCalledTimes(discard ? 1 : 0);
- expect(bindings.discardAllPendingUploads).toHaveBeenCalledTimes(discard ? 1 : 0);
- expect(bindings.releaseUploadedSources).toHaveBeenCalledTimes(discard ? 1 : 0);
- expect(bindings.selectedDeviceIdRef).toEqual({ current: 'new-host' });
- if (discard) expect(bindings.setAttachments).toHaveBeenCalledWith([]);
- else expect(bindings.setAttachments).not.toHaveBeenCalled();
+ 'preserves initial shares with previous host %s (discard=%s)', (previousDeviceId, shouldDiscard) => {
+ discard.mockClear();
+ const shared = newSessionAttachment({ id: 'shared-attachment' });
+ let attachments: RemoteSerializedAttachment[] = [shared];
+ const pending = new Set(['pending-share']);
+ const retained = new Set([shared.id]);
+ const annotations = new Set([shared.id]);
+ clearNewSessionAttachmentsForDeviceChange({
+ previousDeviceId, nextDeviceId: 'new-host', attachments,
+ getToken: async () => 'token', discardAllPendingUploads: () => pending.clear(),
+ releaseUploadedSources: ids => ids.forEach(id => retained.delete(id)),
+ setAttachments: next => { attachments = next; }, setMediaAssetAttachments: () => {},
+ setAttachmentPreviews: () => {}, forgetAllAnnotations: () => annotations.clear(),
+ setAttachmentError: () => {},
+ });
+ expect(discard).toHaveBeenCalledTimes(shouldDiscard ? 1 : 0);
+ expect(attachments).toEqual(shouldDiscard ? [] : [shared]);
+ expect([...pending]).toEqual(shouldDiscard ? [] : ['pending-share']);
+ expect([...retained]).toEqual(shouldDiscard ? [] : [shared.id]);
+ expect([...annotations]).toEqual(shouldDiscard ? [] : [shared.id]);
},
);
-it('keeps shared text when opening plugins without typing first', async () => {
- const { appendComposerPluginTrigger } = await import('@/session/composerPlugins');
- const { textComposerDocument, composerDocumentProjectedText } = await import('@/session/composerDocument');
- const names = ['setFirstMessageDraft', 'patchDraft', 'openPluginPalette'];
- const declarations: string[] = [];
- let appendText = '';
- function collect(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && names.includes(node.name.getText(page))
- && node.initializer && ts.isCallExpression(node.initializer)) {
- declarations.push(`const ${node.name.getText(page)} = ${node.initializer.arguments[0].getText(page)};`);
- }
- if (ts.isCallExpression(node) && node.expression.getText(page) === 'useIncomingShareComposer') {
- const options = node.arguments[0];
- if (ts.isObjectLiteralExpression(options)) {
- const property = options.properties.find(p => ts.isPropertyAssignment(p) && p.name.getText(page) === 'appendText');
- if (property && ts.isPropertyAssignment(property)) appendText = property.initializer.getText(page);
- }
- }
- ts.forEachChild(node, collect);
- }
- collect(page);
- let draft = { firstMessage: 'Existing instruction' };
- const ref = { current: draft.firstMessage };
- const bindings = {
- firstMessageRef: ref, creatingRef: { current: false }, editRecoveredDraft: vi.fn(),
+it('keeps shared text when opening plugins without typing first', () => {
+ let draft = newSessionDraft({ firstMessage: 'Existing instruction' });
+ const firstMessageRef = { current: draft.firstMessage };
+ const editRecoveredDraft = vi.fn();
+ const target = {
+ firstMessageRef, creatingRef: { current: false }, editRecoveredDraft,
voiceDictionaryLearningTrackerRef: { current: null },
- setDraft: (update: (current: typeof draft) => typeof draft) => { draft = update(draft); },
- appendComposerPluginTrigger, textComposerDocument, composerDocumentProjectedText,
- firstMessageSelectionRef: { current: null }, setFirstMessageSelection: vi.fn(),
- composerPillOpen: { onCollapsedPress: vi.fn() },
+ setDraft: (update: NewSessionDraft | ((current: NewSessionDraft) => NewSessionDraft)) => {
+ draft = typeof update === 'function' ? update(draft) : update;
+ },
};
- const source = ts.transpileModule(`${declarations.join('\n')}\nconst appendText = ${appendText};`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
- }).outputText;
- const actions = new Function(...Object.keys(bindings), `${source}; return { appendText, openPluginPalette };`)(...Object.values(bindings));
- actions.appendText('Shared webpage instruction');
- actions.openPluginPalette();
+ appendNewSessionSharedText(target, 'Shared webpage instruction');
+ const selection = { current: { start: 0, end: 0 } };
+ openNewSessionPluginPalette({
+ firstMessageRef, patchDraft: patch => patchNewSessionDraft(target, patch),
+ firstMessageSelectionRef: selection, setFirstMessageSelection: () => {}, focusComposer: () => {},
+ });
expect(draft.firstMessage).toContain('Existing instruction\n\nShared webpage instruction');
- expect(ref.current).toBe(draft.firstMessage);
- expect(bindings.editRecoveredDraft).toHaveBeenCalledWith({ firstMessage: draft.firstMessage });
+ expect(firstMessageRef.current).toBe(draft.firstMessage);
+ expect(selection.current).toEqual({ start: draft.firstMessage.length, end: draft.firstMessage.length });
+ expect(editRecoveredDraft).toHaveBeenCalledWith({ firstMessage: draft.firstMessage });
});
diff --git a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
index eb367b7021..55fe5e2574 100644
--- a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
+++ b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
@@ -1,5 +1,4 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { captureNewSessionOwner } from '@/session/newSessionForm';
import { accountVaultKey } from '@cindy/auth-client';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -86,26 +85,13 @@ describe('newSessionPreferenceStore', () => {
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)];
- 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();
- 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');
- 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');
- }
+ const currentOwner = getMobileAuthOwner();
+ const creation = captureNewSessionOwner(currentOwner, 'shared-member');
+ expect(creation.isCurrentOwner()).toBe(true);
+ expect(creation.worktreeAccountId).toBe('shared-member');
+ setMobileAuthOwner('shared-member', 'global');
+ expect(creation.isCurrentOwner()).toBe(false);
+ expect(captureNewSessionOwner(getMobileAuthOwner(), 'another-member').isCurrentOwner()).toBe(false);
});
it('stores the last selected device and agent for new sessions', async () => {
diff --git a/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx b/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
index e1074047c3..35606609af 100644
--- a/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
@@ -1,12 +1,15 @@
// @vitest-environment jsdom
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
import { act, createElement, createRef, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import type { TextInputProps, TextStyle } from 'react-native';
-import ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { MobileComposerInputRow, type MobileComposerInputRowProps } from '@/session/MobileComposerInputRow';
+import { MobileComposerInputRow } from '@/session/MobileComposerInputRow';
+import {
+ changeNewSessionVoiceSelection, changeNewSessionVoiceText, finishNewSessionVoiceRecording,
+ newSessionVoiceComposerProps, publishNewSessionVoiceDraft,
+ type NewSessionVoiceSelectionInput, type NewSessionVoiceStopInput,
+} from '@/session/newSessionVoiceInput';
+import { deferred } from './fixtures/newSession';
import { palettes } from '@/theme/tokens';
const native = vi.hoisted(() => ({
@@ -54,118 +57,50 @@ vi.mock('@/theme', () => ({
useThemedStyles: (make: (colors: typeof palettes.light) => unknown) => make(palettes[native.mode]),
}));
-// Exercise the page's actual visibility/event expressions and the real input row.
-// Extract only this boundary so unrelated screen/network/native dependencies are not loaded.
-// Native drawing and hit testing still require the Android emulator regression.
-const source = ts.createSourceFile('new.tsx', readFileSync(
- resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8',
-), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-function findOne<T extends ts.Node>(guard: (node: ts.Node) => node is T): T {
- const found: T[] = [];
- function visit(node: ts.Node) {
- if (guard(node)) found.push(node);
- ts.forEachChild(node, visit);
- }
- visit(source);
- if (found.length !== 1) throw new Error(`Expected one source boundary, found ${found.length}`);
- return found[0];
-}
-const hiddenStyle = findOne((node): node is ts.PropertyAssignment =>
- ts.isPropertyAssignment(node) && node.name.getText(source) === 'inputVoiceHidden');
-const composer = findOne((node): node is ts.JsxSelfClosingElement =>
- ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'MobileComposerInputRow');
-const propNames = ['inputStyle', 'caretHidden', 'value', 'placeholder', 'selection', 'onPressIn', 'onKeyPress'];
-function composerExpression(name: string) {
- const prop = composer.attributes.properties.find((node) =>
- ts.isJsxAttribute(node) && node.name.getText(source) === name);
- if (!prop || !ts.isJsxAttribute(prop) || !prop.initializer
- || !ts.isJsxExpression(prop.initializer) || !prop.initializer.expression) {
- throw new Error(`Missing composer expression: ${name}`);
- }
- return prop.initializer.expression.getText(source);
-}
-const expressions = propNames.map((name) => `${name}: ${composerExpression(name)}`);
-const compiled = ts.transpileModule(`function pageProps(bindings) {
- const { Platform, voiceIsListening, draft, finishVoiceRecording, composerPlaceholder, firstMessageSelection,
- voiceStopGestureSelectionGuardRef, voicePendingSelectionEchoesRef } = bindings;
- const styles = { inputVoiceHidden: ${hiddenStyle.initializer.getText(source)} };
- return { ${expressions.join(',\n')} };
-}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
-const pageProps = new Function(`${compiled}; return pageProps;`)() as
- (bindings: Record<string, unknown>) => Partial<MobileComposerInputRowProps>;
-
-// Run the actual page callbacks across a deferred stop(), including native
-// selection echoes and typing, instead of asserting the source of a guard.
-const draftCallback = findOne((node): node is ts.PropertyAssignment =>
- ts.isPropertyAssignment(node) && node.name.getText(source) === 'onDraftChanged');
-const stopCallback = findOne((node): node is ts.VariableDeclaration =>
- ts.isVariableDeclaration(node) && node.name.getText(source) === 'finishVoiceRecording');
-if (!stopCallback.initializer || !ts.isCallExpression(stopCallback.initializer)) {
- throw new Error('Missing finishVoiceRecording callback');
-}
+// Unit: production voice/form functions and the real input row protect delayed
+// selection echoes, typing during stop, and Android's native-text regression.
+// Deferred stop plus a user edit is the minimum timing input. Native drawing and
+// hit testing still require the Android emulator regression.
type Selection = { start: number; end: number };
-const compiledVoice = ts.transpileModule(`function voiceCallbacks(bindings) {
- const { voiceSelectionUserOwnedRef, voiceRecordingActiveRef, voiceStopInFlightRef,
- voiceStopGestureSelectionGuardRef, voicePendingSelectionEchoesRef,
- firstMessageRef, firstMessageSelectionRef, setFirstMessageSelection, setFirstMessageDraft,
- voiceControllerSessionRef, voiceStartupSeqRef, voiceStartupInFlightRef, voiceState,
- setVoiceState, setVoiceError, setAudioModeAsync, requestAnimationFrame,
- firstMessageInputRef, formatRemoteError, voiceIsListening, finishVoiceRecording } = bindings;
- return {
- publish: ${draftCallback.initializer.getText(source)},
- select: ${composerExpression('onSelectionChange')},
- type: ${composerExpression('onChangeText')},
- press: ${composerExpression('onPressIn')},
- key: ${composerExpression('onKeyPress')},
- stop: ${stopCallback.initializer.arguments[0].getText(source)},
- };
-}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
-const voiceCallbacks = new Function(`${compiledVoice}; return voiceCallbacks;`)() as
- (bindings: Record<string, unknown>) => {
- publish: (text: string, selection?: Selection, replacement?: Selection & { text: string }) => void;
- select: (event: { nativeEvent: { selection: Selection } }) => void;
- type: (text: string) => void;
- press: () => void;
- key: () => void;
- stop: () => Promise<string | null>;
- };
function pendingVoiceStop(initialDraft = '前后') {
const firstMessageRef = { current: initialDraft };
const firstMessageSelectionRef = { current: { start: 1, end: 1 } };
let controlledSelection = firstMessageSelectionRef.current;
- let completeStop!: (draft: string) => void;
- let finishVoiceRecording!: () => Promise<string | null>;
let activeStop: Promise<string | null> | undefined;
- const stopGate = new Promise<string>((resolve) => { completeStop = resolve; });
+ const stopGate = deferred<string>();
const setNativeProps = vi.fn();
const bindings = {
firstMessageRef, firstMessageSelectionRef,
voiceSelectionUserOwnedRef: { current: false },
voiceStopGestureSelectionGuardRef: { current: false },
- voicePendingSelectionEchoesRef: { current: [] },
+ voicePendingSelectionEchoesRef: { current: [] as Selection[] },
voiceRecordingActiveRef: { current: true }, voiceStopInFlightRef: { current: false },
voiceStartupSeqRef: { current: 1 }, voiceStartupInFlightRef: { current: false },
- voiceControllerSessionRef: { current: { stop: () => stopGate } },
+ voiceControllerSessionRef: { current: { stop: () => stopGate.promise } },
voiceState: 'listening', setVoiceState: vi.fn(), setVoiceError: vi.fn(),
setFirstMessageSelection: (next: Selection) => { controlledSelection = next; },
setFirstMessageDraft: (text: string) => { firstMessageRef.current = text; },
- setAudioModeAsync: async () => undefined,
requestAnimationFrame: (callback: () => void) => callback(),
firstMessageInputRef: { current: { setNativeProps } }, formatRemoteError: String,
- voiceIsListening: true, finishVoiceRecording: () => {
- activeStop = callbacks.stop();
- return activeStop;
- },
- };
- const callbacks = voiceCallbacks(bindings);
+ } satisfies NewSessionVoiceSelectionInput & NewSessionVoiceStopInput;
+ const stop = () => finishNewSessionVoiceRecording(bindings);
+ const composer = (voiceIsListening: boolean) => newSessionVoiceComposerProps({
+ ...bindings, platform: 'android', voiceIsListening, firstMessage: firstMessageRef.current,
+ firstMessageSelection: controlledSelection, composerPlaceholder: 'Draft',
+ finishVoiceRecording: () => { activeStop = stop(); return activeStop; },
+ });
return {
- ...callbacks,
+ stop,
+ publish: (text: string, selection?: Selection, replacement?: Selection & { text: string }) =>
+ publishNewSessionVoiceDraft(bindings, text, selection, replacement),
+ type: (text: string) => changeNewSessionVoiceText(bindings, text),
+ key: () => composer(true).onKeyPress(),
selection: () => controlledSelection,
- move: (start: number, end = start) => callbacks.select({ nativeEvent: { selection: { start, end } } }),
- complete: () => completeStop(firstMessageRef.current), setNativeProps,
- press: () => { callbacks.press(); return activeStop; },
- pressToEdit: () => voiceCallbacks({ ...bindings, voiceIsListening: false }).press(),
+ move: (start: number, end = start) => changeNewSessionVoiceSelection(bindings, { start, end }),
+ complete: () => stopGate.resolve(firstMessageRef.current), setNativeProps,
+ press: () => { composer(true).onPressIn(); return activeStop; },
+ pressToEdit: () => composer(false).onPressIn(),
insert: (text: string) => firstMessageRef.current.slice(0, controlledSelection.start)
+ text + firstMessageRef.current.slice(controlledSelection.end),
};
@@ -356,10 +291,10 @@ function mountInput() {
const colors = palettes[native.mode];
act(() => root!.render(createElement(MobileComposerInputRow, {
accessibilityLabel: 'Draft', inputTestID: 'draft', inputRef: ref,
- placeholder: 'Draft', placeholderTextColor: colors.textTertiary,
- value: draft, onChangeText: vi.fn(), onPasteImages: vi.fn(),
- ...pageProps({ Platform: { OS: native.platform }, voiceIsListening: listening,
- draft: { firstMessage: draft }, firstMessageSelection: selection,
+ placeholderTextColor: colors.textTertiary,
+ onChangeText: vi.fn(), onPasteImages: vi.fn(),
+ ...newSessionVoiceComposerProps({ platform: native.platform, voiceIsListening: listening,
+ firstMessage: draft, firstMessageSelection: selection,
finishVoiceRecording, composerPlaceholder: 'Draft',
voiceStopGestureSelectionGuardRef: { current: false },
voicePendingSelectionEchoesRef: { current: [] } }),
diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
index 16a86902fc..3750dadb8d 100644
--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
@@ -1,72 +1,30 @@
// @vitest-environment jsdom
-import { isRemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';
import { i18n } from '@/i18n';
-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',
- 'workingDirPreferenceOverridesRef',
- 'preferredDefaultDevice', 'recentWorkspaces', 'draft', 'initialWorkspaceKeyRef',
- 'appliedDefaultDeviceKeyRef', 'userTouchedDeviceRef', 'userTouchedWorkspaceRef',
- 'patchDraft', 'selectWorkingDir', 'rememberWorkingDirForDevice', 'selectDialogueWorkspace',
- 'selectRecentProject', 'openProjectBrowse',
- 'firstMessageRef', 'firstMessageSelectionRef', 'firstMessageSelection',
- 'restoreCreationDraft', 'userTouchedRuntimeRef', 'appliedPermissionMemoryRef',
- 'runtimeActionSeqRef', 'attachments', 'attachmentsRef', 'planModeDraftOn', 'prePlanPermissionModeRef', 'remoteAgentChoice',
-]);
-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}`);
-}
+import { createInitialNewSessionDraft, patchNewSessionDraft, restoreNewSessionDraft } from '@/session/newSessionForm';
+import { useNewSessionStashedDraft, useNewSessionWorkspacePreferences, useNewSessionWorkspaceActions, useNewSessionInitialWorkspace } from '@/session/useNewSessionWorkspace';
+import { readNewSessionPreferences, saveNewSessionPreferences } from '@/session/newSessionPreferenceStore';
+import type { RemoteSerializedAttachment, RemoteSession } from '@/session/types';
+
+vi.mock('@/session/newSessionPreferenceStore', () => ({
+ readNewSessionPreferences: vi.fn(),
+ saveNewSessionPreferences: vi.fn(async () => {}),
+}));
+// Unit: mount production hooks against pending preferences and a visible form.
+// #4103 and mobile-development creation recovery: late defaults must not replace
+// explicit/restored input or borrow another computer's project directory.
interface WorkspaceState {
draft: NewSessionDraft;
firstMessageSelection: { start: number; end: number };
@@ -78,36 +36,6 @@ interface WorkspaceState {
/** 模拟页面 selectDevice 里与工作区相关的部分:标记用户动过设备、重置初始工作区决策、清空项目目录。 */
switchDevice(deviceId: string): void;
}
-const bindingNames = [
- 'useState', 'useRef', 'useMemo', 'useEffect', 'useCallback', 'DEFAULT_NEW_SESSION_DRAFT',
- 'pickNewSessionDefaultDevice', 'buildRecentWorkspaceOptions', 'pickInitialNewSessionWorkspace',
- 'routeDeviceId', 'routeDeviceName', 'routeDeviceFallback', 'routeDeviceExplicit', 'deviceOptions',
- 'isRemoteTaskSuggestionId', 'params', 't',
- 'initialWorkingDir', 'visualInitialDraft', 'sessions', 'readNewSessionPreferences',
- 'saveNewSessionPreferences', 'drainStashedNewSessionDraft', 'loadBrowsePath', 'setDevicePickerOpen',
- 'setAttachmentError', 'setBrowseOpen', 'setBrowseError',
- 'setShowHiddenDirectories', 'setWorkspacePickerOpen',
- 'editRecoveredDraft', 'creatingRef', 'voiceDictionaryLearningTrackerRef',
-];
-const readRouteString = source.statements.find((node): node is ts.FunctionDeclaration =>
- ts.isFunctionDeclaration(node) && node.name?.text === 'readRouteString');
-if (!readRouteString) throw new Error('readRouteString not found');
-const compiled = ts.transpileModule(`${readRouteString.getText(source)}
-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,
- firstMessageSelection, selectDialogueWorkspace, selectRecentProject, openProjectBrowse, switchDevice };
-}`, { 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; });
@@ -119,32 +47,83 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Ne
const initialWorkingDir = options.initialWorkingDir ?? null;
const bindings = {
editRecoveredDraft: vi.fn(), creatingRef: { current: false }, voiceDictionaryLearningTrackerRef: { current: null },
- isRemoteTaskSuggestionId, params: { suggestion: options.suggestion, draft: options.routeDraft, editSessionId: options.restoredKind ? 'failed-task' : undefined }, t: i18n.getFixedT('zh-CN'),
- useState, useRef, useMemo, useEffect, useCallback, DEFAULT_NEW_SESSION_DRAFT,
- pickNewSessionDefaultDevice, buildRecentWorkspaceOptions,
- pickInitialNewSessionWorkspace: vi.fn(pickInitialNewSessionWorkspace),
+ params: { suggestion: options.suggestion, draft: options.routeDraft, editSessionId: options.restoredKind ? 'failed-task' : undefined }, t: i18n.getFixedT('zh-CN'),
routeDeviceId: 'a', routeDeviceName: 'A', routeDeviceFallback: deviceOptions[0],
routeDeviceExplicit: options.deviceExplicit ?? !!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 () => {}),
+ } as RemoteSession)),
+ readNewSessionPreferences, saveNewSessionPreferences,
drainStashedNewSessionDraft: vi.fn((sessionId?: string, deviceId?: string) => options.restoredKind && sessionId === 'failed-task' && deviceId === 'a' ? {
draft: { ...DEFAULT_NEW_SESSION_DRAFT, workspaceKind: options.restoredKind,
workingDir: options.restoredKind === 'project' ? '/restored/project' : '',
firstMessage: 'restored draft' },
- attachments: [], deviceId: 'a', deviceName: 'A',
+ attachments: [], deviceId: 'a', deviceName: 'A', notice: null, collabDraft: null,
} : 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(),
};
+ vi.mocked(readNewSessionPreferences).mockImplementation(() => pendingRead);
+ vi.mocked(saveNewSessionPreferences).mockClear();
let current!: WorkspaceState;
const commits: Array<{ device: string; kind: NewSessionWorkspaceKind; path: string }> = [];
function Harness() {
- current = usePageWorkspace(bindings);
+ const [selectedDeviceId, setSelectedDeviceId] = useState(bindings.routeDeviceId);
+ const [, setSelectedDeviceName] = useState(bindings.routeDeviceName);
+ const [newSessionPreferences, setNewSessionPreferences] = useState<NewSessionStoredPreferences | null>(null);
+ const [newSessionPreferencesLoaded, setNewSessionPreferencesLoaded] = useState(false);
+ const [draft, setDraft] = useState(() => createInitialNewSessionDraft({
+ initialWorkingDir, visualInitialDraft: null, routeDraft: options.routeDraft,
+ suggestion: options.suggestion, t: bindings.t,
+ }));
+ const workingDirPreferenceOverridesRef = useRef<Record<string, string>>({});
+ const initialWorkspaceKeyRef = useRef<string | null>(null);
+ const appliedDefaultDeviceKeyRef = useRef<string | null>(null);
+ const userTouchedDeviceRef = useRef(false);
+ const userTouchedWorkspaceRef = useRef(false);
+ const userTouchedRuntimeRef = useRef(false);
+ const appliedPermissionMemoryRef = useRef(false);
+ const runtimeActionSeqRef = useRef(0);
+ const firstMessageRef = useRef(draft.firstMessage);
+ const firstMessageSelectionRef = useRef({ start: draft.firstMessage.length, end: draft.firstMessage.length });
+ const [firstMessageSelection, setFirstMessageSelection] = useState(firstMessageSelectionRef.current);
+ const attachmentsRef = useRef<RemoteSerializedAttachment[]>([]);
+ const prePlanPermissionModeRef = useRef<string | null>(null);
+ const restoreCreationDraft = useCallback((...args: Parameters<typeof restoreNewSessionDraft> extends [unknown, ...infer Rest] ? Rest : never) => {
+ restoreNewSessionDraft({ userTouchedWorkspaceRef, userTouchedRuntimeRef, appliedPermissionMemoryRef,
+ runtimeActionSeqRef, firstMessageRef, firstMessageSelectionRef, setFirstMessageSelection,
+ attachmentsRef, prePlanPermissionModeRef, setAttachments: bindings.setAttachments,
+ setPlanModeDraftOn: () => {}, setRemoteAgentChoice: () => {}, setDraft }, ...args);
+ }, []);
+ const preferredDefaultDevice = useMemo(() => pickNewSessionDefaultDevice({
+ deviceOptions, preferredDeviceId: newSessionPreferences?.device?.deviceId,
+ routeDevice: bindings.routeDeviceFallback, routeDeviceExplicit: bindings.routeDeviceExplicit,
+ }), [newSessionPreferences]);
+ const recentWorkspaces = useMemo(() => buildRecentWorkspaceOptions(
+ bindings.sessions.filter(session => session.deviceLinkDeviceId === selectedDeviceId), selectedDeviceId,
+ ), [selectedDeviceId]);
+ const common = { ...bindings, selectedDeviceId, setSelectedDeviceId, setSelectedDeviceName,
+ newSessionPreferences, setNewSessionPreferences, newSessionPreferencesLoaded, setNewSessionPreferencesLoaded,
+ workingDirPreferenceOverridesRef, initialWorkspaceKeyRef, appliedDefaultDeviceKeyRef,
+ userTouchedDeviceRef, userTouchedWorkspaceRef, draft, setDraft, preferredDefaultDevice };
+ useNewSessionStashedDraft({ ...common, sessionId: bindings.params.editSessionId, deviceId: 'a',
+ restoreCreationDraft, onRestoreCollab: () => {} });
+ useNewSessionWorkspacePreferences(common);
+ const patchDraft = useCallback((patch: Partial<NewSessionDraft>) => patchNewSessionDraft({
+ ...bindings, firstMessageRef, setDraft,
+ }, patch), []);
+ const actions = useNewSessionWorkspaceActions({ ...common, patchDraft });
+ useNewSessionInitialWorkspace({ ...common, recentWorkspaces, selectWorkingDir: actions.selectWorkingDir });
+ current = { draft, selectedDeviceId, newSessionPreferencesLoaded, firstMessageSelection, ...actions,
+ switchDevice: deviceId => {
+ userTouchedDeviceRef.current = true;
+ initialWorkspaceKeyRef.current = null;
+ setSelectedDeviceId(deviceId);
+ setDraft(value => value.workspaceKind === 'project' ? { ...value, workingDir: '' } : value);
+ },
+ };
useEffect(() => {
commits.push({ device: current.selectedDeviceId, kind: current.draft.workspaceKind,
path: current.draft.workingDir });
@@ -229,7 +208,6 @@ describe('new session workspace page effects', () => {
workingDir: kind === 'project' ? '/restored/project' : '' });
expect(page.current.selectedDeviceId).toBe('a');
expect(page.current.firstMessageSelection).toEqual({ start: 'restored draft'.length, end: 'restored draft'.length });
- expect(page.bindings.pickInitialNewSessionWorkspace).not.toHaveBeenCalled();
});
it.each(['project', 'dialogue'] as const)('preserves a manual %s choice made during the read', async (kind) => {
@@ -258,11 +236,9 @@ describe('new session workspace page effects', () => {
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' },
]);
@@ -275,7 +251,6 @@ describe('new session workspace page effects', () => {
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() }),
@@ -307,6 +282,5 @@ describe('new session workspace page effects', () => {
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/__tests__/newSessionWorktreeSync.test.tsx b/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
index 5c32182b5f..1de5cea876 100644
--- a/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
@@ -1,185 +1,147 @@
// @vitest-environment jsdom
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { act, createElement, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { remoteSessionStore, useRemoteNewMakerWorktreePreference } from '@/session/remoteSessionStore';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { NewSessionWorktreeEligibility } from '@/session/newSessionWorktree';
import {
- applyWorktreePreferenceOnHost, classifyWorktreePreferenceSeed, isWorktreeChannelNotAllowedError,
- shouldBlockNewSessionCreateForWorktree, worktreeEligibilityCaptionKey,
- type NewSessionWorktreeEligibility,
-} from '@/session/newSessionWorktree';
-import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
+ useNewSessionWorktreeSync,
+ type NewSessionWorktreeSyncInput,
+ type WorktreeCreateIntentSnapshot,
+} from '@/session/useNewSessionWorktreeSync';
+import { deferred, newSessionDraft } from './fixtures/newSession';
-// Exercise the page's actual hooks and both entry guards. Extract AST statements
-// (as in newSessionWorkspaceEffects), avoiding a parallel implementation of the gates.
-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');
-function names(node: ts.Node): Set<string> {
- const found = new Set<string>();
- function visit(child: ts.Node) {
- if (ts.isIdentifier(child)) found.add(child.text);
- ts.forEachChild(child, visit);
- }
- visit(node);
- return found;
-}
-const declarations = new Set([
- 'worktreePreference', 'worktreeChoicesRef', 'setWorktreeChoiceVersion', 'worktreeEnabled',
- 'worktreeEnabledRef', 'worktreeSeedSeqRef', 'worktreeSeedRetryNonce',
- 'worktreePreferenceSyncKeyRef', 'worktreePreferenceWriteSeqRef',
- 'worktreePreferenceWriteTargetRef', 'worktreePreferenceSavingDeviceId',
- 'worktreePreferenceTransactionRef', 'worktreePreferenceRenderedRef',
- 'worktreePreferenceAuthorityUnknownByDeviceRef', 'setWorktreePreferenceAuthorityVersion',
- 'worktreePreferenceSaving', 'worktreePreferenceSyncKey', 'worktreePreferenceAuthorityUnknown',
- 'worktreeApplicable', 'worktreeToggleDisabled', 'worktreeCreateBlocked', 'worktreeCaptionKey',
- 'worktreeControlCaptionKey', 'resolveWorktreeCreateErrorKey',
- 'captureWorktreeCreateIntent', 'isWorktreeCreateIntentCurrent', 'worktreeSeedAgentKindRef',
- 'worktreeHostSupportsRecoveryKeyDiscardRef', 'worktreePreferenceAwaitingEcho', 'toggleWorktree',
-]);
-const hooks = page.body.statements.filter((statement) => {
- if (ts.isVariableStatement(statement)) return statement.declarationList.declarations.some(
- (declaration) => [...names(declaration.name)].some((name) => declarations.has(name)),
- );
- if (!ts.isExpressionStatement(statement)) return false;
- const expr = statement.expression;
- if (ts.isBinaryExpression(expr)) return [
- 'worktreeEnabledRef.current', 'worktreePreferenceSyncKeyRef.current',
- 'worktreeSeedAgentKindRef.current', 'worktreeHostSupportsRecoveryKeyDiscardRef.current',
- ].includes(expr.left.getText(source));
- if (!ts.isCallExpression(expr) || !['useEffect', 'useLayoutEffect'].includes(expr.expression.getText(source))) return false;
- const ids = names(statement);
- return ids.has('worktreeSeedSeqRef') || ids.has('worktreePreferenceAuthorityUnknownByDeviceRef')
- || ids.has('worktreePreferenceRenderedRef');
-});
-for (const name of declarations) {
- if (!hooks.some((node) => ts.isVariableStatement(node) && node.declarationList.declarations.some(
- (declaration) => names(declaration.name).has(name),
- ))) throw new Error(`Missing page worktree declaration: ${name}`);
-}
-function entryGuards(name: string): string {
- const statement = page!.body!.statements.find((node) => ts.isVariableStatement(node)
- && node.declarationList.declarations.some((decl) => decl.name.getText(source) === name)) as ts.VariableStatement;
- const call = statement.declarationList.declarations[0].initializer as ts.CallExpression;
- const callback = call.arguments[0] as ts.ArrowFunction;
- const body = callback.body as ts.Block;
- const end = body.statements.findIndex((node) => ts.isExpressionStatement(node)
- && node.expression.getText(source) === 'creatingRef.current = true');
- if (end < 0) throw new Error(`Missing create boundary: ${name}`);
- const guards = body.statements.slice(0, end).filter((node) =>
- [...names(node)].some((id) => /^(worktree|captureWorktree|isWorktree)/.test(id)));
- if (!guards.some((node) => names(node).has('worktreeIntent'))) throw new Error(`Missing intent: ${name}`);
- return `function ${name}() { ${guards.map((node) => node.getText(source)).join('\n')} return worktreeIntent; }`;
-}
-const bindingsNames = [
- 'useState', 'useRef', 'useEffect', 'useLayoutEffect', 'useCallback',
- 'remoteSessionStore', 'useRemoteNewMakerWorktreePreference', 'applyWorktreePreferenceOnHost',
- 'classifyWorktreePreferenceSeed', 'isWorktreeChannelNotAllowedError', 'withTransientRemoteRetry',
- 'shouldBlockNewSessionCreateForWorktree', 'worktreeEligibilityCaptionKey',
- 'selectedDeviceId', 'connectionEpoch', 'presenceVersion', 'deviceLinkStatus', 'deviceLinkStatusRef',
- 'creating', 'creatingRef', 'draft', 'maker', 'openLink', 'worktreeEligibility',
- 'worktreeHostSupportsRecoveryKeyDiscard', 'worktreeBranchPreferenceSaving',
- 'worktreeBranchPreferenceReady', 'worktreeBranchPreferenceReadyKeyRef',
- 'worktreeBranchPreferenceError', 'worktreeBranchPreferenceKey', 'worktreeBranchPreferenceSyncKey',
- 'worktreeBranchPreferenceSyncKeyRef', 'worktreeBranchPreferenceWriteTargetRef',
- 'worktreeBranchPreferenceTransactionRef', 'worktreeBranchTargetRef',
- 'worktreeEligibilityRef', 'worktreeSourceBranchRef', 't', 'setError', 'setGoalError',
-];
-const compiled = ts.transpileModule(`function usePageWorktree(bindings) {
- const { ${bindingsNames.join(', ')} } = bindings;
- ${hooks.map((node) => node.getText(source)).join('\n')}
- ${entryGuards('createMessageSession')}
- ${entryGuards('createGoalSession')}
- return { worktreeEnabled, worktreeCreateBlocked, worktreeToggleDisabled,
- worktreePreferenceSaving, worktreePreferenceAuthorityUnknown,
- toggleWorktree, create: createMessageSession, createGoalSession, isWorktreeCreateIntentCurrent };
-}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
-interface Intent { enabled: boolean; sourceBranch: string; target: { deviceId: string } }
-interface State {
- worktreeEnabled: boolean;
- worktreeCreateBlocked: boolean;
- worktreeToggleDisabled: boolean;
- worktreePreferenceSaving: boolean;
- worktreePreferenceAuthorityUnknown: boolean;
- toggleWorktree(): void;
+// Unit: exercise the production hook and shared preparation guard used by message
+// and goal creation. Protect same-tick explicit choices, late defaults/echoes,
+// reconnects, and changed targets. The old AST-extraction harness missed module
+// dependencies and could keep passing after page integration drifted.
+type Intent = WorktreeCreateIntentSnapshot;
+type State = ReturnType<typeof useNewSessionWorktreeSync> & {
create(): Intent | undefined;
createGoalSession(): Intent | undefined;
- isWorktreeCreateIntentCurrent(intent: Intent): boolean;
-}
-const usePageWorktree = new Function(`${compiled}; return usePageWorktree;`)() as
- (bindings: Record<string, unknown>) => State;
+};
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
-afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ vi.useRealTimers();
+});
let deviceSequence = 0;
-function deferred<T>() {
- let resolve!: (value: T) => void;
- let reject!: (error: Error) => void;
- const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
- return { promise, resolve, reject };
-}
function mount(remembered?: boolean) {
const deviceId = `worktree-sync-${++deviceSequence}`;
- if (remembered !== undefined) remoteSessionStore.setNewMakerWorktreePreference(deviceId, remembered);
+ if (remembered !== undefined)
+ remoteSessionStore.setNewMakerWorktreePreference(deviceId, remembered);
const read = deferred<{ worktreeEnabled?: boolean }>();
const write = deferred<void>();
- const eligibility: NewSessionWorktreeEligibility = { status: 'eligible', baseRepo: '/repo', sourceBranch: 'main' };
+ const eligibility: NewSessionWorktreeEligibility = {
+ status: 'eligible',
+ baseRepo: '/repo',
+ sourceBranch: 'main',
+ };
const bindings = {
- useState, useRef, useEffect, useLayoutEffect, useCallback,
- remoteSessionStore, useRemoteNewMakerWorktreePreference, applyWorktreePreferenceOnHost,
- classifyWorktreePreferenceSeed, isWorktreeChannelNotAllowedError, withTransientRemoteRetry,
- shouldBlockNewSessionCreateForWorktree, worktreeEligibilityCaptionKey,
- selectedDeviceId: deviceId, connectionEpoch: 1, presenceVersion: 1,
- deviceLinkStatus: 'online', deviceLinkStatusRef: { current: 'online' },
- creating: false, creatingRef: { current: false },
- draft: { workspaceKind: 'project', workingDir: '/repo', agentKind: 'codex' },
- maker: { getNewMakerDefaults: vi.fn(() => read.promise), applyNewMakerWorktreePref: vi.fn(() => write.promise) },
- openLink: vi.fn(async () => {}), worktreeEligibility: eligibility as NewSessionWorktreeEligibility,
+ selectedDeviceId: deviceId,
+ connectionEpoch: 1,
+ presenceVersion: 1,
+ deviceLinkStatus: 'online',
+ deviceLinkStatusRef: { current: 'online' },
+ creating: false,
+ creatingRef: { current: false },
+ draft: newSessionDraft({
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ agentKind: 'codex',
+ }),
+ maker: {
+ getNewMakerDefaults: vi.fn(() => read.promise),
+ applyNewMakerWorktreePref: vi.fn(() => write.promise),
+ },
+ openLink: vi.fn(async () => {}),
+ worktreeEligibility: eligibility as NewSessionWorktreeEligibility,
worktreeHostSupportsRecoveryKeyDiscard: true,
- worktreeBranchPreferenceSaving: false, worktreeBranchPreferenceError: false,
+ worktreeBranchPreferenceSaving: false,
+ worktreeBranchPreferenceError: false,
worktreeBranchPreferenceReady: true,
- worktreeBranchPreferenceReadyKeyRef: { current: 'branch-generation' as string | null },
- worktreeBranchPreferenceKey: `${deviceId}\0/repo`, worktreeBranchPreferenceSyncKey: 'branch-generation',
+ worktreeBranchPreferenceReadyKeyRef: {
+ current: 'branch-generation' as string | null,
+ },
+ worktreeBranchPreferenceKey: `${deviceId}\0/repo`,
+ worktreeBranchPreferenceSyncKey: 'branch-generation',
worktreeBranchPreferenceSyncKeyRef: { current: 'branch-generation' },
worktreeBranchPreferenceWriteTargetRef: { current: null as string | null },
- worktreeBranchPreferenceTransactionRef: { current: null },
+ worktreeBranchPreferenceTransactionRef: {
+ current: null,
+ } as NewSessionWorktreeSyncInput['worktreeBranchPreferenceTransactionRef'],
worktreeBranchTargetRef: { current: { deviceId, workingDir: '/repo' } },
- worktreeEligibilityRef: { current: eligibility as NewSessionWorktreeEligibility }, worktreeSourceBranchRef: { current: 'main' },
- t: (key: string) => key, setError: vi.fn(), setGoalError: vi.fn(),
+ worktreeEligibilityRef: {
+ current: eligibility as NewSessionWorktreeEligibility,
+ },
+ worktreeSourceBranchRef: { current: 'main' },
+ setError: vi.fn(),
+ setGoalError: vi.fn(),
};
let state!: State;
- function Harness() { state = usePageWorktree(bindings); return null; }
+ function Harness() {
+ const worktree = useNewSessionWorktreeSync(bindings);
+ state = {
+ ...worktree,
+ create: () => worktree.prepareWorktreeCreateIntent(bindings.setError),
+ createGoalSession: () =>
+ worktree.prepareWorktreeCreateIntent(bindings.setGoalError),
+ };
+ return null;
+ }
root = createRoot(document.createElement('div'));
const render = () => act(() => root!.render(createElement(Harness)));
render();
- return { bindings, read, write, render, deviceId, get state() { return state; } };
+ return {
+ bindings,
+ read,
+ write,
+ render,
+ deviceId,
+ get state() {
+ return state;
+ },
+ };
}
for (const entry of ['create', 'createGoalSession'] as const) {
describe(entry, () => {
- it.each([undefined, false, true])('uses displayed value %s without waiting for defaults', async (remembered) => {
- const h = mount(remembered);
- await act(async () => {});
- expect(h.bindings.maker.getNewMakerDefaults).toHaveBeenCalledWith('codex');
- expect(h.state.worktreeCreateBlocked).toBe(false);
- expect(h.state.worktreeToggleDisabled).toBe(false);
- expect(h.state[entry]()).toMatchObject({ enabled: remembered ?? false, sourceBranch: 'main' });
- await act(async () => { h.read.resolve({}); });
- expect(h.state[entry]()).toMatchObject({ enabled: remembered ?? false });
- });
+ it.each([undefined, false, true])(
+ 'uses displayed value %s without waiting for defaults',
+ async (remembered) => {
+ const h = mount(remembered);
+ await act(async () => {});
+ expect(h.bindings.maker.getNewMakerDefaults).toHaveBeenCalledWith(
+ 'codex',
+ );
+ expect(h.state.worktreeCreateBlocked).toBe(false);
+ expect(h.state.worktreeToggleDisabled).toBe(false);
+ expect(h.state[entry]()).toMatchObject({
+ enabled: remembered ?? false,
+ sourceBranch: 'main',
+ });
+ await act(async () => {
+ h.read.resolve({});
+ });
+ expect(h.state[entry]()).toMatchObject({
+ enabled: remembered ?? false,
+ });
+ },
+ );
it('uses a same-tick explicit toggle while saving, and ignores a late opposite default', async () => {
const h = mount(false);
let intent!: Intent;
- act(() => { h.state.toggleWorktree(); intent = h.state[entry]()!; });
+ act(() => {
+ h.state.toggleWorktree();
+ intent = h.state[entry]()!;
+ });
expect(intent.enabled).toBe(true);
- expect(h.bindings.maker.applyNewMakerWorktreePref).toHaveBeenCalledWith(true);
+ expect(h.bindings.maker.applyNewMakerWorktreePref).toHaveBeenCalledWith(
+ true,
+ );
expect(h.state.worktreePreferenceSaving).toBe(true);
expect(h.state.worktreeCreateBlocked).toBe(false);
await act(async () => {
@@ -189,7 +151,9 @@ for (const entry of ['create', 'createGoalSession'] as const) {
expect(h.state.worktreeEnabled).toBe(true);
expect(h.state.isWorktreeCreateIntentCurrent(intent)).toBe(true);
expect(h.state[entry]()?.enabled).toBe(true);
- await act(async () => { h.write.reject(new Error('timeout')); });
+ await act(async () => {
+ h.write.reject(new Error('timeout'));
+ });
expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
expect(h.state[entry]()?.enabled).toBe(true);
expect(h.state.worktreeToggleDisabled).toBe(false);
@@ -198,18 +162,24 @@ for (const entry of ['create', 'createGoalSession'] as const) {
it('can turn a remembered ON value off and immediately send despite failed detection', () => {
const h = mount(true);
h.bindings.worktreeEligibility = { status: 'detect-failed' };
- h.bindings.worktreeEligibilityRef.current = h.bindings.worktreeEligibility;
+ h.bindings.worktreeEligibilityRef.current =
+ h.bindings.worktreeEligibility;
h.render();
expect(h.state.worktreeCreateBlocked).toBe(true);
let intent: Intent | undefined;
- act(() => { h.state.toggleWorktree(); intent = h.state[entry](); });
+ act(() => {
+ h.state.toggleWorktree();
+ intent = h.state[entry]();
+ });
expect(intent?.enabled).toBe(false);
});
it('freezes submission while allowing untouched defaults to refresh for the next attempt', async () => {
const h = mount(false);
const intent = h.state[entry]()!;
- await act(async () => { h.read.resolve({ worktreeEnabled: true }); });
+ await act(async () => {
+ h.read.resolve({ worktreeEnabled: true });
+ });
expect(h.state.worktreeEnabled).toBe(true);
expect(intent.enabled).toBe(false);
expect(h.state.isWorktreeCreateIntentCurrent(intent)).toBe(true);
@@ -226,10 +196,14 @@ for (const entry of ['create', 'createGoalSession'] as const) {
h.bindings.worktreeBranchPreferenceError = true;
h.render();
expect(h.state[entry]()).toBeUndefined();
- expect(entry === 'create' ? h.bindings.setError : h.bindings.setGoalError)
- .toHaveBeenLastCalledWith('session.new.worktreeBranchSyncFailed');
+ expect(
+ entry === 'create' ? h.bindings.setError : h.bindings.setGoalError,
+ ).toHaveBeenLastCalledWith('session.new.worktreeBranchSyncFailed');
let intent: Intent | undefined;
- act(() => { h.state.toggleWorktree(); intent = h.state[entry](); });
+ act(() => {
+ h.state.toggleWorktree();
+ intent = h.state[entry]();
+ });
expect(intent?.enabled).toBe(false);
});
@@ -241,7 +215,8 @@ for (const entry of ['create', 'createGoalSession'] as const) {
expect(h.state[entry]()).toBeUndefined();
h.bindings.worktreeSourceBranchRef.current = 'release';
h.bindings.worktreeBranchPreferenceReady = true;
- h.bindings.worktreeBranchPreferenceReadyKeyRef.current = 'branch-generation';
+ h.bindings.worktreeBranchPreferenceReadyKeyRef.current =
+ 'branch-generation';
h.render();
expect(h.state[entry]()?.sourceBranch).toBe('release');
});
@@ -249,12 +224,19 @@ for (const entry of ['create', 'createGoalSession'] as const) {
it('keeps genuine eligibility and explicit branch-write failures blocking an enabled worktree', () => {
const h = mount(true);
h.bindings.worktreeEligibility = { status: 'detect-failed' };
- h.bindings.worktreeEligibilityRef.current = h.bindings.worktreeEligibility;
+ h.bindings.worktreeEligibilityRef.current =
+ h.bindings.worktreeEligibility;
h.render();
expect(h.state[entry]()).toBeUndefined();
- h.bindings.worktreeEligibility = { status: 'eligible', baseRepo: '/repo', sourceBranch: 'main' };
- h.bindings.worktreeEligibilityRef.current = h.bindings.worktreeEligibility;
- h.bindings.worktreeBranchPreferenceWriteTargetRef.current = h.bindings.worktreeBranchPreferenceKey;
+ h.bindings.worktreeEligibility = {
+ status: 'eligible',
+ baseRepo: '/repo',
+ sourceBranch: 'main',
+ };
+ h.bindings.worktreeEligibilityRef.current =
+ h.bindings.worktreeEligibility;
+ h.bindings.worktreeBranchPreferenceWriteTargetRef.current =
+ h.bindings.worktreeBranchPreferenceKey;
h.render();
expect(h.state[entry]()).toBeUndefined();
});
@@ -264,10 +246,15 @@ for (const entry of ['create', 'createGoalSession'] as const) {
it('bounds an accepted write with no persistence echo, without ever blocking send', async () => {
vi.useFakeTimers();
const h = mount(false);
- await act(async () => { h.state.toggleWorktree(); h.write.resolve(); });
+ await act(async () => {
+ h.state.toggleWorktree();
+ h.write.resolve();
+ });
expect(h.state.worktreePreferenceSaving).toBe(true);
expect(h.state.create()?.enabled).toBe(true);
- await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
expect(h.state.worktreePreferenceSaving).toBe(false);
expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
expect(h.state.worktreeEnabled).toBe(true);
@@ -275,7 +262,9 @@ it('bounds an accepted write with no persistence echo, without ever blocking sen
it('keeps remembered values usable after a read failure and reconnection', async () => {
const h = mount(true);
- await act(async () => { h.read.reject(new Error('invalid defaults response')); });
+ await act(async () => {
+ h.read.reject(new Error('invalid defaults response'));
+ });
expect(h.state.create()?.enabled).toBe(true);
h.bindings.connectionEpoch += 1;
h.render();
@@ -287,7 +276,10 @@ it('does not leak an explicit choice to another device, or accept a changed crea
act(() => h.state.toggleWorktree());
const intent = h.state.create()!;
h.bindings.selectedDeviceId = `other-${h.deviceId}`;
- h.bindings.worktreeBranchTargetRef.current = { deviceId: h.bindings.selectedDeviceId, workingDir: '/other' };
+ h.bindings.worktreeBranchTargetRef.current = {
+ deviceId: h.bindings.selectedDeviceId,
+ workingDir: '/other',
+ };
h.render();
expect(h.state.worktreeEnabled).toBe(false);
expect(h.state.isWorktreeCreateIntentCurrent(intent)).toBe(false);
@@ -296,30 +288,46 @@ it('does not leak an explicit choice to another device, or accept a changed crea
it('settles an authoritative echo that arrives before the apply response', async () => {
const h = mount(false);
act(() => h.state.toggleWorktree());
- await act(async () => { remoteSessionStore.setNewMakerWorktreePreference(h.deviceId, true); });
- await act(async () => { h.write.resolve(); });
+ await act(async () => {
+ remoteSessionStore.setNewMakerWorktreePreference(h.deviceId, true);
+ });
+ await act(async () => {
+ h.write.resolve();
+ });
expect(h.state.worktreePreferenceSaving).toBe(false);
expect(h.state.worktreePreferenceAuthorityUnknown).toBe(false);
});
-it.each(['writing', 'reconciling'])('retains device A uncertainty when device B replaces a %s write', async (phase) => {
- const h = mount(false);
- act(() => h.state.toggleWorktree());
- if (phase === 'reconciling') await act(async () => { h.write.resolve(); });
- const secondWrite = deferred<void>();
- h.bindings.maker.applyNewMakerWorktreePref = vi.fn(() => secondWrite.promise);
- h.bindings.selectedDeviceId = `other-${h.deviceId}`;
- h.render();
- act(() => h.state.toggleWorktree());
- h.bindings.selectedDeviceId = h.deviceId;
- h.render();
- expect(h.state.worktreeEnabled).toBe(true);
- expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
- expect(h.state.create()?.enabled).toBe(true);
- expect(h.state.createGoalSession()?.enabled).toBe(true);
- await act(async () => { h.write.resolve(); });
- expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
- await act(async () => { remoteSessionStore.setNewMakerWorktreePreference(h.deviceId, true); });
- expect(h.state.worktreePreferenceAuthorityUnknown).toBe(false);
- expect(h.state.worktreeEnabled).toBe(true);
-});
+it.each(['writing', 'reconciling'])(
+ 'retains device A uncertainty when device B replaces a %s write',
+ async (phase) => {
+ const h = mount(false);
+ act(() => h.state.toggleWorktree());
+ if (phase === 'reconciling')
+ await act(async () => {
+ h.write.resolve();
+ });
+ const secondWrite = deferred<void>();
+ h.bindings.maker.applyNewMakerWorktreePref = vi.fn(
+ () => secondWrite.promise,
+ );
+ h.bindings.selectedDeviceId = `other-${h.deviceId}`;
+ h.render();
+ act(() => h.state.toggleWorktree());
+ h.bindings.selectedDeviceId = h.deviceId;
+ h.render();
+ expect(h.state.worktreeEnabled).toBe(true);
+ expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
+ expect(h.state.create()?.enabled).toBe(true);
+ expect(h.state.createGoalSession()?.enabled).toBe(true);
+ await act(async () => {
+ h.write.resolve();
+ });
+ expect(h.state.worktreePreferenceAuthorityUnknown).toBe(true);
+ await act(async () => {
+ remoteSessionStore.setNewMakerWorktreePreference(h.deviceId, true);
+ });
+ expect(h.state.worktreePreferenceAuthorityUnknown).toBe(false);
+ expect(h.state.worktreeEnabled).toBe(true);
+ },
+);
diff --git a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
index bf891c2b8f..d725667be8 100644
--- a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
+++ b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
@@ -1,8 +1,6 @@
// @vitest-environment jsdom
+import { markNewSessionIncomingShare } from '@/session/newSessionForm';
import { act, useState } from 'react';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
@@ -313,33 +311,16 @@ it.each(['edited', 'cleared', 'failed'] as const)('keeps the edit claim through
}
});
-// Execute the page's real latch against delayed durable recovery. A global
-// share must not make this composer own input destined for another screen.
-const newPage = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),
- ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let shareLatchSource = '';
-function findShareLatch(node: ts.Node) {
- if (ts.isIfStatement(node) && ts.isExpressionStatement(node.thenStatement)
- && ts.isBinaryExpression(node.thenStatement.expression)
- && node.thenStatement.expression.left.getText(newPage) === 'incomingShareReceivedRef.current') {
- shareLatchSource = node.getText(newPage);
- }
- ts.forEachChild(node, findShareLatch);
-}
-findShareLatch(newPage);
-if (!shareLatchSource) throw new Error('Missing new-task share ownership latch');
-const applyShareLatch = new Function('incomingShareBatch', 'incomingShareReceivedRef',
- ts.transpileModule(shareLatchSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText);
-
+// Unit: a share for another screen must not claim this form or suppress recovery.
it.each([undefined, 'device/task', 'companion/task', 'new'])(
'only protects the new-task draft for its selected share destination: %s', async destination => {
const received = { current: false };
resume.hasInput = () => received.current;
await renderBlank();
- applyShareLatch({ id: 'share' }, received);
- if (destination) applyShareLatch({ id: 'share', destination }, received);
+ markNewSessionIncomingShare({}, received);
+ if (destination) markNewSessionIncomingShare({ destination }, received);
// Cancellation or successful handoff removes the global batch.
- applyShareLatch(null, received);
+ markNewSessionIncomingShare(null, received);
await act(async () => ready());
await notify();
expect(container.textContent).toBe(destination === 'new' ? '' : 'device/task');
diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsx
index 77d8564bd4..8944c38e8c 100644
--- a/apps/mobile/src/session/MobileOutboxBridge.tsx
+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx
@@ -9,8 +9,6 @@ import {
} from "@/auth/authOwnerGeneration";
import { useDeviceLink } from "@/device-link/DeviceLinkContext";
import { parseSharedTaskPeer } from "@cindy/device-link";
-import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
-import { cindyMakeOutboxPolicy } from './cindyMakeOutboxPolicy';
import {
createMobileMakerTransport,
type RemoteInvoke,
@@ -41,9 +39,7 @@ import {
} from "./mobileAttachmentUpload";
import { buildQueuedTextMessage, EMPTY_INPUT_PROJECTION } from "./inputProjection";
import { mobileDebugLog } from "@/debug/mobileDebugLog";
-import type { RemoteSession } from "./types";
import { outboxItemAttachments } from "./sessionOutbox";
-import { sessionFromCreateResult } from "./newSession";
import { dismissRecoveredPrecreatedSession, getNewSessionCreationTask, restoreNewSessionDurableEdit } from "./newSessionCreation";
import {
MobileSessionReferenceError,
@@ -53,14 +49,13 @@ import { remoteSessionStore } from "./remoteSessionStore";
import { cacheOutboxHistory } from "./outboxHistoryCache";
import { validateOutboxResourceBinding } from './outboxResourceBinding';
import { findRemoteHistoryView } from "./remoteHistoryViews";
+import type { DurableOutboxRecord } from "./durableOutbox";
import {
- isDurableOutboxHandedOff,
- isDurableOutboxSettled,
- type DurableOutboxRecord,
-} from "./durableOutbox";
-
-/** One authoritative session read serves the policy check and preparation of the same attempt. */
-const SESSION_READ_REUSE_MS = 2_000;
+ createOutboxMessageLeases,
+ createOutboxSessionAccess,
+ outboxNeedsReconciliation,
+ outboxSessionKey,
+} from "./mobileOutboxSessionAdapter";
/** Runs only while the OS gives the app execution time; foreground/reconnect resume the same ledger. */
export function MobileOutboxBridge() {
@@ -95,11 +90,23 @@ export function MobileOutboxBridge() {
const guard = () => {
if (!isCurrent()) throw new Error("OUTBOX_OWNER_CHANGED");
};
- const knownSession = (record: DurableOutboxRecord) =>
- remoteSessionStore.getSessions().find(session =>
- session.id === record.item.sessionId && session.deviceLinkDeviceId === record.deviceId);
- const hidden = (record: DurableOutboxRecord) =>
- !CINDY_MAKE_ENABLED && isCindyMakeSource(knownSession(record)?.source);
+ const needsReconciliation = (record: DurableOutboxRecord) =>
+ outboxNeedsReconciliation(record,
+ findRemoteHistoryView(record.deviceId, record.item.sessionId)?.isActive() === true);
+ const { hidden, invokeOwned, readSessionOnce, canRun, sessionPolicy } = createOutboxSessionAccess({
+ getSessions: () => remoteSessionStore.getSessions(),
+ getRecords: () => mobileDurableOutbox.getSnapshot(),
+ isCurrent,
+ guard,
+ invoke: (deviceId, channel, args, options) => latest.current.link.invoke(deviceId, channel, args, options),
+ readSession: (record) => maker(record).getSession(record.item.sessionId),
+ isForeground: () => AppState.currentState !== "background" && AppState.currentState !== "inactive",
+ canConnect: (deviceId) => latest.current.link.status === "online"
+ && latest.current.link.getPresenceAvailability(deviceId) !== false,
+ isCreationHeld: isDurableOutboxCreationHeld,
+ hasCreationTask: (sessionId) => getNewSessionCreationTask(sessionId) !== null,
+ needsReconciliation,
+ });
const invoke: RemoteInvoke = async (deviceId, channel, args) => {
guard();
const result = await latest.current.link.invoke(deviceId, channel, args, {
@@ -108,49 +115,11 @@ export function MobileOutboxBridge() {
guard();
return result as never;
};
- const invokeOwned =
- (record: DurableOutboxRecord): RemoteInvoke =>
- async (deviceId, channel, args) => {
- const guardRecord = () => {
- guard();
- if (!mobileDurableOutbox.getSnapshot().includes(record))
- throw new Error("OUTBOX_STALE_WRITE");
- if (hidden(record)) throw new Error('OUTBOX_SESSION_DISABLED');
- };
- guardRecord();
- const result = await latest.current.link.invoke(
- deviceId,
- channel,
- args,
- { preSend: guardRecord },
- );
- guardRecord();
- return result as never;
- };
const maker = (r: DurableOutboxRecord) =>
createMobileMakerTransport({
deviceId: r.deviceId,
invoke: invokeOwned(r),
});
- // The policy check and message preparation both need the authoritative
- // session row; one read serves both within a single delivery attempt.
- // Keyed per message: each read runs under that message's ownership guard.
- const sessionReads = new Map<string, { at: number; read: Promise<RemoteSession> }>();
- const readSessionOnce = (r: DurableOutboxRecord): Promise<RemoteSession> => {
- const key = JSON.stringify([r.deviceId, r.item.sessionId, r.item.clientId]);
- const now = Date.now();
- // Only reads inside the reuse window are useful; drop the rest so the map stays tiny.
- for (const [other, entry] of sessionReads)
- if (now - entry.at >= SESSION_READ_REUSE_MS) sessionReads.delete(other);
- const cached = sessionReads.get(key);
- if (cached) return cached.read;
- const read = maker(r).getSession(r.item.sessionId);
- sessionReads.set(key, { at: now, read });
- read.catch(() => {
- if (sessionReads.get(key)?.read === read) sessionReads.delete(key);
- });
- return read;
- };
// Learned from this host's own projection / enqueue replies. A first send in
// a task whose boundary is known needs no projection round trip.
const durableHosts = new Set<string>();
@@ -176,12 +145,7 @@ export function MobileOutboxBridge() {
}
};
const epochs = new Map<string, { authority: number; remote: number }>();
- const leases = new Map<
- string,
- ReturnType<typeof remoteSessionStore.acquireSessionMessageWork>
- >();
- const leaseKey = (r: DurableOutboxRecord) =>
- JSON.stringify([r.deviceId, r.item.sessionId]);
+ const leaseKey = outboxSessionKey;
const captureProjectionEpoch = (r: DurableOutboxRecord) => {
epochs.set(leaseKey(r), {
authority: remoteSessionStore.captureInputProjectionAuthorityEpoch(
@@ -192,75 +156,20 @@ export function MobileOutboxBridge() {
),
});
};
- // Accepted sends remain durable in the outbox while hidden. Neither poll
- // their history nor pin their raw message windows just for display handoff.
- const needsReconciliation = (r: DurableOutboxRecord) =>
- !isDurableOutboxHandedOff(r) || r.cancelRequested
- || findRemoteHistoryView(r.deviceId, r.item.sessionId)?.isActive() === true;
- const refreshLeases = () => {
- if (!isCurrent()) return;
- const keys = new Set<string>();
- for (const record of mobileDurableOutbox.getSnapshot()) {
- if (isDurableOutboxSettled(record) || hidden(record)) continue;
- if (restoreNewSessionDurableEdit(record)) continue;
- if (record.creation?.cancelled) {
- dismissRecoveredPrecreatedSession({ sessionId: record.item.sessionId, deviceId: record.deviceId });
- continue;
- }
- if (
- record.creation &&
- !remoteSessionStore
- .getSessions()
- .some((s) => s.id === record.item.sessionId)
- ) {
- remoteSessionStore.upsertDeviceSession(
- record.deviceId,
- record.creation.deviceName,
- sessionFromCreateResult(
- { sessionId: record.item.sessionId },
- {
- ...record.creation.draft,
- attachments: outboxItemAttachments(record.item),
- },
- ),
- );
- }
- if (!needsReconciliation(record)) continue;
- const key = leaseKey(record);
- keys.add(key);
- if (!leases.has(key))
- leases.set(
- key,
- remoteSessionStore.acquireSessionMessageWork(
- record.item.sessionId,
- true,
- ),
- );
- }
- for (const [key, lease] of leases)
- if (!keys.has(key)) {
- lease.release();
- leases.delete(key);
- }
- };
+ const messageLeases = createOutboxMessageLeases({
+ isCurrent,
+ getRecords: () => mobileDurableOutbox.getSnapshot(),
+ hidden,
+ needsReconciliation,
+ restoreEditable: restoreNewSessionDurableEdit,
+ dismissCancelled: dismissRecoveredPrecreatedSession,
+ store: remoteSessionStore,
+ });
const delivery = createDurableOutboxDelivery({
store: mobileDurableOutbox,
isCurrent,
- canRun: (r) =>
- AppState.currentState !== "background" &&
- AppState.currentState !== "inactive" &&
- (hidden(r) || isDurableOutboxSettled(r) ||
- (!r.suspended && !r.creation?.cancelled &&
- needsReconciliation(r) &&
- !isDurableOutboxCreationHeld(r.item.sessionId) &&
- latest.current.link.status === "online" &&
- latest.current.link.getPresenceAvailability(r.deviceId) !== false &&
- getNewSessionCreationTask(r.item.sessionId) === null)),
- sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {
- knownSession: () => knownSession(record),
- readSession: () => readSessionOnce(record),
- isCurrent: () => isCurrent() && mobileDurableOutbox.getSnapshot().includes(record),
- }),
+ canRun,
+ sessionPolicy,
projection: async (r) => {
captureProjectionEpoch(r);
return invoke<DeliveryProjection>(
@@ -453,7 +362,7 @@ export function MobileOutboxBridge() {
});
runnerRef.current = delivery;
const run = () => {
- refreshLeases();
+ messageLeases.refresh();
// Scavenging failure blocks new copies, not already-owned messages' delivery.
void initializeOutboxFiles()
.catch(() => undefined)
@@ -483,7 +392,7 @@ export function MobileOutboxBridge() {
offSessions();
clearInterval(timer);
appState.remove();
- for (const lease of leases.values()) lease.release();
+ messageLeases.dispose();
};
}, [accountId, owner]);
useEffect(() => {
diff --git a/apps/mobile/src/session/mobileOutboxSessionAdapter.ts b/apps/mobile/src/session/mobileOutboxSessionAdapter.ts
new file mode 100644
index 0000000000..ffdccd026f
--- /dev/null
+++ b/apps/mobile/src/session/mobileOutboxSessionAdapter.ts
@@ -0,0 +1,155 @@
+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';
+import { cindyMakeOutboxPolicy } from './cindyMakeOutboxPolicy';
+import { isDurableOutboxHandedOff, isDurableOutboxSettled, type DurableOutboxRecord } from './durableOutbox';
+import { sessionFromCreateResult } from './newSession';
+import type { remoteSessionStore } from './remoteSessionStore';
+import { outboxItemAttachments } from './sessionOutbox';
+import type { RemoteSession } from './types';
+
+type SessionSource = Pick<RemoteSession, 'id' | 'source' | 'deviceLinkDeviceId'>;
+type OutboxLease = ReturnType<typeof remoteSessionStore.acquireSessionMessageWork>;
+
+const findOutboxSession = (record: DurableOutboxRecord, sessions: readonly SessionSource[]) =>
+ sessions.find((session) => session.id === record.item.sessionId && session.deviceLinkDeviceId === record.deviceId);
+
+export function outboxSessionIsHidden(record: DurableOutboxRecord, sessions: readonly SessionSource[]): boolean {
+ return !CINDY_MAKE_ENABLED && isCindyMakeSource(findOutboxSession(record, sessions)?.source);
+}
+
+export function outboxSessionKey(record: DurableOutboxRecord): string {
+ return JSON.stringify([record.deviceId, record.item.sessionId]);
+}
+
+/** Accepted hidden sends stay durable without pinning their raw history window. */
+export function outboxNeedsReconciliation(record: DurableOutboxRecord, isHistoryActive: boolean): boolean {
+ return !isDurableOutboxHandedOff(record) || !!record.cancelRequested || isHistoryActive;
+}
+
+export interface OutboxSessionAccessDeps {
+ getSessions(): readonly SessionSource[];
+ getRecords(): readonly DurableOutboxRecord[];
+ isCurrent(): boolean;
+ guard(): void;
+ invoke(
+ deviceId: string,
+ channel: string,
+ args: unknown[] | undefined,
+ options: { preSend(): void },
+ ): Promise<unknown>;
+ readSession(record: DurableOutboxRecord): Promise<RemoteSession>;
+ isForeground(): boolean;
+ canConnect(deviceId: string): boolean;
+ isCreationHeld(sessionId: string): boolean;
+ hasCreationTask(sessionId: string): boolean;
+ needsReconciliation(record: DurableOutboxRecord): boolean;
+}
+
+/** The bridge and tests use the same ownership, visibility and delivery decisions. */
+export function createOutboxSessionAccess(deps: OutboxSessionAccessDeps) {
+ const knownSession = (record: DurableOutboxRecord) => findOutboxSession(record, deps.getSessions());
+ const hidden = (record: DurableOutboxRecord) => outboxSessionIsHidden(record, deps.getSessions());
+ const invokeOwned =
+ (record: DurableOutboxRecord): RemoteInvoke =>
+ async (deviceId, channel, args) => {
+ const guardRecord = () => {
+ deps.guard();
+ if (!deps.getRecords().includes(record)) throw new Error('OUTBOX_STALE_WRITE');
+ if (hidden(record)) throw new Error('OUTBOX_SESSION_DISABLED');
+ };
+ guardRecord();
+ const result = await deps.invoke(deviceId, channel, args, {
+ preSend: guardRecord,
+ });
+ guardRecord();
+ return result as never;
+ };
+ // Existing per-attempt reuse: policy and preparation share one guarded read.
+ const sessionReads = new Map<string, { at: number; read: Promise<RemoteSession> }>();
+ const readSessionOnce = (record: DurableOutboxRecord): Promise<RemoteSession> => {
+ const key = JSON.stringify([record.deviceId, record.item.sessionId, record.item.clientId]);
+ const now = Date.now();
+ for (const [other, entry] of sessionReads) if (now - entry.at >= 2_000) sessionReads.delete(other);
+ const cached = sessionReads.get(key);
+ if (cached) return cached.read;
+ const read = deps.readSession(record);
+ sessionReads.set(key, { at: now, read });
+ read.catch(() => {
+ if (sessionReads.get(key)?.read === read) sessionReads.delete(key);
+ });
+ return read;
+ };
+ const canRun = (record: DurableOutboxRecord) =>
+ deps.isForeground() &&
+ (hidden(record) ||
+ isDurableOutboxSettled(record) ||
+ (!record.suspended &&
+ !record.creation?.cancelled &&
+ deps.needsReconciliation(record) &&
+ !deps.isCreationHeld(record.item.sessionId) &&
+ deps.canConnect(record.deviceId) &&
+ !deps.hasCreationTask(record.item.sessionId)));
+ const sessionPolicy = (record: DurableOutboxRecord) =>
+ cindyMakeOutboxPolicy(record, {
+ knownSession: () => knownSession(record),
+ readSession: () => readSessionOnce(record),
+ isCurrent: () => deps.isCurrent() && deps.getRecords().includes(record),
+ });
+ return { hidden, invokeOwned, readSessionOnce, canRun, sessionPolicy };
+}
+
+export interface OutboxMessageLeaseDeps {
+ isCurrent(): boolean;
+ getRecords(): readonly DurableOutboxRecord[];
+ hidden(record: DurableOutboxRecord): boolean;
+ needsReconciliation(record: DurableOutboxRecord): boolean;
+ restoreEditable(record: DurableOutboxRecord): boolean;
+ dismissCancelled(record: { sessionId: string; deviceId: string }): void;
+ store: Pick<typeof remoteSessionStore, 'getSessions' | 'upsertDeviceSession' | 'acquireSessionMessageWork'>;
+}
+
+/** Restore the existing creation projection and retain only message work still in use. */
+export function createOutboxMessageLeases(deps: OutboxMessageLeaseDeps) {
+ const leases = new Map<string, OutboxLease>();
+ const refresh = () => {
+ if (!deps.isCurrent()) return;
+ const keys = new Set<string>();
+ for (const record of deps.getRecords()) {
+ if (isDurableOutboxSettled(record) || deps.hidden(record)) continue;
+ if (deps.restoreEditable(record)) continue;
+ if (record.creation?.cancelled) {
+ deps.dismissCancelled({
+ sessionId: record.item.sessionId,
+ deviceId: record.deviceId,
+ });
+ continue;
+ }
+ if (record.creation && !deps.store.getSessions().some((session) => session.id === record.item.sessionId)) {
+ deps.store.upsertDeviceSession(
+ record.deviceId,
+ record.creation.deviceName,
+ sessionFromCreateResult(
+ { sessionId: record.item.sessionId },
+ {
+ ...record.creation.draft,
+ attachments: outboxItemAttachments(record.item),
+ },
+ ),
+ );
+ }
+ if (!deps.needsReconciliation(record)) continue;
+ const key = outboxSessionKey(record);
+ keys.add(key);
+ if (!leases.has(key)) leases.set(key, deps.store.acquireSessionMessageWork(record.item.sessionId, true));
+ }
+ for (const [key, lease] of leases)
+ if (!keys.has(key)) {
+ lease.release();
+ leases.delete(key);
+ }
+ };
+ const dispose = () => {
+ for (const lease of leases.values()) lease.release();
+ };
+ return { leases, refresh, dispose };
+}
diff --git a/apps/mobile/src/session/newSessionAttachmentCleanup.ts b/apps/mobile/src/session/newSessionAttachmentCleanup.ts
index 015aacd87f..927ab4917f 100644
--- a/apps/mobile/src/session/newSessionAttachmentCleanup.ts
+++ b/apps/mobile/src/session/newSessionAttachmentCleanup.ts
@@ -1,5 +1,33 @@
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { discardMobileUploadedAttachment } from '@/session/mobileAttachmentUpload';
+import type { RemoteSerializedAttachment } from './types';
+
+/** Shares uploaded before choosing a computer remain usable on the first selection. */
+export function clearNewSessionAttachmentsForDeviceChange(input: {
+ previousDeviceId: string;
+ nextDeviceId: string;
+ attachments: RemoteSerializedAttachment[];
+ getToken: () => Promise<string | null>;
+ discardAllPendingUploads: () => void;
+ releaseUploadedSources: (ids: string[]) => void;
+ setAttachments: (attachments: RemoteSerializedAttachment[]) => void;
+ setMediaAssetAttachments: (value: Record<string, string>) => void;
+ setAttachmentPreviews: (value: Record<string, string>) => void;
+ forgetAllAnnotations: () => void;
+ setAttachmentError: (value: string | null) => void;
+}): void {
+ if (!input.previousDeviceId || input.previousDeviceId === input.nextDeviceId) return;
+ for (const attachment of input.attachments) {
+ discardMobileUploadedAttachment(attachment, { getToken: input.getToken });
+ }
+ input.discardAllPendingUploads();
+ input.releaseUploadedSources(input.attachments.map(attachment => attachment.id));
+ input.setAttachments([]);
+ input.setMediaAssetAttachments({});
+ input.setAttachmentPreviews({});
+ input.forgetAllAnnotations();
+ input.setAttachmentError(null);
+}
/** Best-effort reclaim before the account-change callback drops draft references. */
export function discardNewSessionUploadedAttachments(
diff --git a/apps/mobile/src/session/newSessionForm.ts b/apps/mobile/src/session/newSessionForm.ts
new file mode 100644
index 0000000000..cd3306207f
--- /dev/null
+++ b/apps/mobile/src/session/newSessionForm.ts
@@ -0,0 +1,205 @@
+import type { Dispatch, RefObject, SetStateAction } from "react";
+import {
+ isMobileAuthOwnerCurrent,
+ type MobileAuthOwnerGeneration,
+} from "@/auth/authOwnerGeneration";
+import type { RemoteSerializedAttachment } from "@/session/types";
+import {
+ DEFAULT_NEW_SESSION_DRAFT,
+ type NewSessionDraft,
+ type NewSessionRemoteAgentPick,
+} from "./newSession";
+import { isRemoteTaskSuggestionId } from "./remoteTaskSuggestionsModel";
+import { appendComposerPluginTrigger } from "./composerPlugins";
+import {
+ composerDocumentProjectedText,
+ textComposerDocument,
+} from "./composerDocument";
+
+export function readNewSessionRouteString(value: unknown): string | null {
+ if (typeof value === "string" && value.length > 0) return value;
+ if (
+ Array.isArray(value) &&
+ typeof value[0] === "string" &&
+ value[0].length > 0
+ )
+ return value[0];
+ return null;
+}
+
+export function createInitialNewSessionDraft(input: {
+ initialWorkingDir: string | null;
+ visualInitialDraft: string | null;
+ routeDraft: unknown;
+ suggestion: unknown;
+ t: (key: string) => string;
+}): NewSessionDraft {
+ return {
+ ...DEFAULT_NEW_SESSION_DRAFT,
+ firstMessage:
+ input.visualInitialDraft ??
+ readNewSessionRouteString(input.routeDraft) ??
+ (isRemoteTaskSuggestionId(input.suggestion)
+ ? input.t(
+ `devices.list.taskSuggestions.items.${input.suggestion}.prompt`,
+ )
+ : DEFAULT_NEW_SESSION_DRAFT.firstMessage),
+ workspaceKind: input.initialWorkingDir ? "project" : "dialogue",
+ workingDir: input.initialWorkingDir ?? "",
+ };
+}
+
+export type NewSessionSelection = { start: number; end: number };
+export type NewSessionRemoteAgentChoice = {
+ controlledDeviceId: string;
+ pick: NewSessionRemoteAgentPick;
+ restored?: true;
+} | null;
+
+export interface NewSessionDraftRestoreTarget {
+ userTouchedWorkspaceRef: RefObject<boolean>;
+ userTouchedRuntimeRef: RefObject<boolean>;
+ appliedPermissionMemoryRef: RefObject<boolean>;
+ runtimeActionSeqRef: RefObject<number>;
+ firstMessageRef: RefObject<string>;
+ firstMessageSelectionRef: RefObject<NewSessionSelection>;
+ attachmentsRef: RefObject<RemoteSerializedAttachment[]>;
+ prePlanPermissionModeRef: RefObject<string | null>;
+ setRemoteAgentChoice: (choice: NewSessionRemoteAgentChoice) => void;
+ setFirstMessageSelection: (selection: NewSessionSelection) => void;
+ setAttachments: (files: RemoteSerializedAttachment[]) => void;
+ setPlanModeDraftOn: (enabled: boolean) => void;
+ setDraft: (draft: NewSessionDraft) => void;
+}
+
+/** Restore refs and visible state together, before composer actions can read the draft. */
+export function restoreNewSessionDraft(
+ target: NewSessionDraftRestoreTarget,
+ saved: NewSessionDraft,
+ files: RemoteSerializedAttachment[],
+ plan?: { enabled: boolean; restorePermissionMode: string | null },
+ controlledDeviceId?: string,
+): void {
+ const { agentDeviceId, ...recovered } = saved;
+ target.setRemoteAgentChoice(
+ agentDeviceId && controlledDeviceId
+ ? {
+ controlledDeviceId,
+ pick: {
+ deviceId: agentDeviceId,
+ agentKind: saved.agentKind,
+ model: saved.model,
+ providerId: saved.providerId,
+ effort: saved.effort,
+ fastMode: saved.fastMode,
+ },
+ }
+ : null,
+ );
+ target.userTouchedWorkspaceRef.current = true;
+ target.userTouchedRuntimeRef.current = true;
+ target.appliedPermissionMemoryRef.current = true;
+ target.runtimeActionSeqRef.current += 1;
+ target.firstMessageRef.current = recovered.firstMessage;
+ const selection = {
+ start: recovered.firstMessage.length,
+ end: recovered.firstMessage.length,
+ };
+ target.firstMessageSelectionRef.current = selection;
+ target.setFirstMessageSelection(selection);
+ target.attachmentsRef.current = files;
+ target.setAttachments(files);
+ if (plan) {
+ target.setPlanModeDraftOn(plan.enabled);
+ target.prePlanPermissionModeRef.current = plan.restorePermissionMode;
+ }
+ target.setDraft(recovered);
+}
+
+/** A share claimed by another screen must not suppress this form's draft recovery. */
+export function markNewSessionIncomingShare(
+ batch: { destination?: string } | null | undefined,
+ received: RefObject<boolean>,
+): void {
+ if (batch?.destination === "new") received.current = true;
+}
+
+/** Both normal and goal creation keep the same account-generation boundary. */
+export function captureNewSessionOwner(
+ owner: MobileAuthOwnerGeneration,
+ accountId: string,
+) {
+ return {
+ worktreeAccountId: owner.accountId,
+ isCurrentOwner: () =>
+ owner.accountId === accountId && isMobileAuthOwnerCurrent(owner),
+ };
+}
+
+export interface NewSessionDraftEditTarget {
+ firstMessageRef: RefObject<string>;
+ creatingRef: RefObject<boolean>;
+ editRecoveredDraft: (patch: { firstMessage: string }) => unknown;
+ voiceDictionaryLearningTrackerRef: RefObject<{
+ inspectDraft(text: string): void;
+ } | null>;
+ setDraft: Dispatch<SetStateAction<NewSessionDraft>>;
+}
+
+/** Text input, system shares and plugin insertion all keep durable edits and refs in sync. */
+export function patchNewSessionDraft(
+ target: NewSessionDraftEditTarget,
+ patch: Partial<NewSessionDraft>,
+): void {
+ if (patch.firstMessage !== undefined) {
+ target.firstMessageRef.current = patch.firstMessage;
+ if (!target.creatingRef.current)
+ target.editRecoveredDraft({ firstMessage: patch.firstMessage });
+ target.voiceDictionaryLearningTrackerRef.current?.inspectDraft(
+ patch.firstMessage,
+ );
+ }
+ target.setDraft((current) => ({ ...current, ...patch }));
+}
+
+export function setNewSessionFirstMessage(
+ target: NewSessionDraftEditTarget,
+ next: SetStateAction<string>,
+): void {
+ const value =
+ typeof next === "function" ? next(target.firstMessageRef.current) : next;
+ // Keep the ordering of the text-input path: publish the draft before dictionary inspection.
+ target.firstMessageRef.current = value;
+ if (!target.creatingRef.current)
+ target.editRecoveredDraft({ firstMessage: value });
+ target.setDraft((current) => ({ ...current, firstMessage: value }));
+ target.voiceDictionaryLearningTrackerRef.current?.inspectDraft(value);
+}
+
+export function appendNewSessionSharedText(
+ target: NewSessionDraftEditTarget,
+ text: string,
+): void {
+ setNewSessionFirstMessage(target, (current) =>
+ [current, text].filter(Boolean).join("\n\n"),
+ );
+}
+
+export function openNewSessionPluginPalette(target: {
+ firstMessageRef: RefObject<string>;
+ patchDraft: (patch: Partial<NewSessionDraft>) => void;
+ firstMessageSelectionRef: RefObject<NewSessionSelection>;
+ setFirstMessageSelection: (selection: NewSessionSelection) => void;
+ focusComposer: () => void;
+}): void {
+ const next = composerDocumentProjectedText(
+ appendComposerPluginTrigger(
+ textComposerDocument(target.firstMessageRef.current),
+ ),
+ );
+ target.patchDraft({ firstMessage: next });
+ const selection = { start: next.length, end: next.length };
+ target.firstMessageSelectionRef.current = selection;
+ target.setFirstMessageSelection(selection);
+ target.focusComposer();
+}
diff --git a/apps/mobile/src/session/newSessionRuntimeReconciliation.ts b/apps/mobile/src/session/newSessionRuntimeReconciliation.ts
new file mode 100644
index 0000000000..01e2425cd4
--- /dev/null
+++ b/apps/mobile/src/session/newSessionRuntimeReconciliation.ts
@@ -0,0 +1,238 @@
+import type { Dispatch, SetStateAction } from "react";
+import type { DeviceProvidersPayload } from "@/device-link/deviceProvidersCache";
+import { isCindyAutoModelId } from "@cindy/model-providers/provider-identity";
+import { modelNeedsReselection } from "./modelReselection";
+import {
+ assertSubmitModelResolved,
+ reconcileEffortAfterFallback,
+ resolveRecentModelAndProvider,
+ type NewSessionDraft,
+ type SubmitGuardCatalog,
+} from "./newSession";
+import {
+ buildMobileModelSections,
+ flattenProviderSections,
+ isFastRestorable,
+ type ProviderModelRow,
+} from "./providerModelSections";
+import type { draftModelMemoryFor } from "./draftModelMemory";
+
+type HiddenModelText = (key: string, options: { model: string }) => string;
+
+/** Background catalog refresh preserves an untouched selection unless its source moved. */
+export function reconcileNewSessionCatalogDraft(
+ current: NewSessionDraft,
+ modelRows: readonly ProviderModelRow[],
+ deviceProviders: DeviceProvidersPayload,
+): NewSessionDraft {
+ if (
+ !current.providerId &&
+ !(current.agentKind === "pi" && isCindyAutoModelId(current.model))
+ )
+ return current;
+ const resolved = resolveRecentModelAndProvider(
+ modelRows,
+ { model: current.model, providerId: current.providerId },
+ current.agentKind,
+ true,
+ deviceProviders.providers,
+ deviceProviders.modelVisibilityOverrides,
+ );
+ const pairChanged =
+ resolved.model !== current.model ||
+ resolved.providerId !== current.providerId;
+ if (!pairChanged) return current;
+ // 组合变化时同步校准 effort(codex review P2)、fastMode 保守置 false(可手动重开)。
+ return {
+ ...current,
+ model: resolved.model,
+ providerId: resolved.providerId,
+ effort: reconcileEffortAfterFallback(modelRows, resolved, current.effort),
+ ...(current.fastMode ? { fastMode: false } : {}),
+ };
+}
+
+/** Normal and goal creation use the same final source/model/runtime decision. */
+export function reconcileNewSessionSubmitDraft(
+ effectiveDraft: NewSessionDraft,
+ g: SubmitGuardCatalog,
+ hasFast: () => boolean,
+ t: HiddenModelText,
+): NewSessionDraft {
+ if (
+ g.catalogKnown &&
+ modelNeedsReselection(
+ g.visibilityOverrides,
+ effectiveDraft.agentKind,
+ effectiveDraft.model,
+ effectiveDraft.providerId,
+ )
+ ) {
+ throw new Error(
+ t("session.common.modelHiddenReselect", { model: effectiveDraft.model }),
+ );
+ }
+ const resolved = resolveRecentModelAndProvider(
+ g.rows,
+ { model: effectiveDraft.model, providerId: effectiveDraft.providerId },
+ effectiveDraft.agentKind,
+ g.catalogKnown,
+ g.providers,
+ g.visibilityOverrides,
+ );
+ assertSubmitModelResolved(resolved, effectiveDraft.model);
+ const pairChanged =
+ resolved.model !== effectiveDraft.model ||
+ resolved.providerId !== effectiveDraft.providerId;
+ // 目录就绪时**始终**按 fresh 精确行校准(codex review P2:来源未变时也按
+ // 新目录校准运行选项)——provider revision 可能只改能力不删行(撤销 effort
+ // 档位 / Fast 支持),组合不变沿用旧 effort/fastMode 会发送目录已不支持的
+ // 参数被被控端拒绝。fail-open(catalogKnown=false)时 rows 不可信,保持
+ // 信任语义(不校准,仅组合变化保守关 fast)。
+ return {
+ ...effectiveDraft,
+ ...resolved,
+ ...(g.catalogKnown
+ ? {
+ effort: reconcileEffortAfterFallback(
+ g.rows,
+ resolved,
+ effectiveDraft.effort,
+ ),
+ ...(effectiveDraft.fastMode &&
+ (pairChanged ||
+ !resolved.providerId ||
+ !isFastRestorable(
+ effectiveDraft.agentKind,
+ resolved.providerId,
+ resolved.model,
+ g.rows,
+ hasFast(),
+ effectiveDraft.fastMode,
+ ))
+ ? { fastMode: false }
+ : {}),
+ }
+ : pairChanged
+ ? {
+ ...(effectiveDraft.fastMode ? { fastMode: false } : {}),
+ }
+ : {}),
+ };
+}
+
+/** Revalidate against the newly authenticated catalog before the background handoff. */
+export function revalidateNewSessionDraftAfterAuth(
+ effectiveDraft: NewSessionDraft,
+ fresh: DeviceProvidersPayload,
+ hasFast: () => boolean,
+ t: HiddenModelText,
+): Partial<NewSessionDraft> {
+ const rows = flattenProviderSections(
+ buildMobileModelSections({
+ providers: fresh.providers,
+ agentKind: effectiveDraft.agentKind,
+ visibilityOverrides: fresh.modelVisibilityOverrides,
+ selectedModelId: effectiveDraft.model,
+ selectedProviderId: effectiveDraft.providerId,
+ }).sections,
+ );
+ const next = reconcileNewSessionSubmitDraft(
+ effectiveDraft,
+ {
+ rows,
+ providers: fresh.providers,
+ catalogKnown: true,
+ visibilityOverrides: fresh.modelVisibilityOverrides,
+ genAt: 0,
+ },
+ hasFast,
+ t,
+ );
+ return {
+ model: next.model,
+ providerId: next.providerId,
+ effort: next.effort,
+ ...(next.fastMode !== effectiveDraft.fastMode
+ ? { fastMode: next.fastMode }
+ : {}),
+ };
+}
+
+/** Restore a remembered speed only when the target Agent's current capabilities allow it. */
+export function restoreNewSessionFastPreference({
+ selectedDeviceId,
+ draft,
+ activeSourceId,
+ capabilitiesKnown,
+ catalogReady,
+ modelRows,
+ hasFast,
+ draftMemory,
+ setDraft,
+}: {
+ selectedDeviceId: string;
+ draft: NewSessionDraft;
+ activeSourceId: string | null;
+ capabilitiesKnown: boolean;
+ catalogReady: boolean;
+ modelRows: readonly ProviderModelRow[];
+ hasFast: () => boolean;
+ draftMemory: Pick<ReturnType<typeof draftModelMemoryFor>, "getFast">;
+ setDraft: Dispatch<SetStateAction<NewSessionDraft>>;
+}): void {
+ if (!selectedDeviceId) return;
+ // 来源 id 与 changeSelectedFastMode 同口径:显式选了来源用 providerId,默认路由
+ // (null)草稿可用推断来源(activeSourceIdRef)开启 Fast——撤销检查不得漏掉它
+ // (codex review P2:目录 revision 改变默认来源/移除 Fast 支持时,null-provider
+ // 草稿仍在发 fastMode:true)。
+ const pid = draft.providerId ?? activeSourceId;
+ if (!pid) return;
+ const capsKnown = capabilitiesKnown;
+ if (draft.fastMode) {
+ if (
+ capsKnown &&
+ catalogReady &&
+ !isFastRestorable(
+ draft.agentKind,
+ pid,
+ draft.model,
+ modelRows,
+ hasFast(),
+ draft.fastMode,
+ )
+ ) {
+ setDraft((current) =>
+ current.fastMode &&
+ current.agentKind === draft.agentKind &&
+ current.model === draft.model &&
+ current.providerId === draft.providerId
+ ? { ...current, fastMode: false }
+ : current,
+ );
+ }
+ return;
+ }
+ const rememberedFast =
+ draftMemory.getFast(draft.agentKind, pid, draft.model) ?? false;
+ if (!rememberedFast) return;
+ if (
+ !isFastRestorable(
+ draft.agentKind,
+ pid,
+ draft.model,
+ modelRows,
+ hasFast(),
+ rememberedFast,
+ )
+ )
+ return;
+ setDraft((current) =>
+ !current.fastMode &&
+ current.agentKind === draft.agentKind &&
+ current.model === draft.model &&
+ current.providerId === draft.providerId
+ ? { ...current, fastMode: rememberedFast }
+ : current,
+ );
+}
diff --git a/apps/mobile/src/session/newSessionVoiceInput.ts b/apps/mobile/src/session/newSessionVoiceInput.ts
new file mode 100644
index 0000000000..0f15039f11
--- /dev/null
+++ b/apps/mobile/src/session/newSessionVoiceInput.ts
@@ -0,0 +1,220 @@
+import type { RefObject } from "react";
+import type { MobileComposerInputRowProps } from "./MobileComposerInputRow";
+import type { MobileVoiceControllerSession } from "./mobileVoiceController";
+import type { MobileVoiceState } from "./mobileVoiceInput";
+
+type Selection = { start: number; end: number };
+
+const hiddenVoiceInputStyle = { color: "transparent" };
+// Android Fabric can treat transparent as unset; keep layout and presses.
+const hiddenAndroidVoiceInputStyle = { ...hiddenVoiceInputStyle, opacity: 0 };
+
+export interface NewSessionVoiceSelectionInput {
+ voiceSelectionUserOwnedRef: RefObject<boolean>;
+ voiceRecordingActiveRef: RefObject<boolean>;
+ voiceStopInFlightRef: RefObject<boolean>;
+ voiceStopGestureSelectionGuardRef: RefObject<boolean>;
+ voicePendingSelectionEchoesRef: RefObject<Selection[]>;
+ firstMessageRef: RefObject<string>;
+ firstMessageSelectionRef: RefObject<Selection>;
+ setFirstMessageSelection(selection: Selection): void;
+ setFirstMessageDraft(text: string): void;
+}
+
+/** Follow ASR until a native edit claims the caret, then rebase it with the voice range. */
+export function publishNewSessionVoiceDraft(
+ input: NewSessionVoiceSelectionInput,
+ text: string,
+ selection?: Selection,
+ replacement?: Selection & { text: string },
+): void {
+ let nextSelection = input.voiceSelectionUserOwnedRef.current
+ ? undefined
+ : selection;
+ if (input.voiceSelectionUserOwnedRef.current && replacement) {
+ const replacementEnd = replacement.start + replacement.text.length;
+ const rebaseOffset = (offset: number) => {
+ if (offset <= replacement.start) return offset;
+ if (offset >= replacement.end)
+ return offset + replacementEnd - replacement.end;
+ return Math.min(offset, replacementEnd);
+ };
+ const current = input.firstMessageSelectionRef.current;
+ nextSelection = {
+ start: rebaseOffset(current.start),
+ end: rebaseOffset(current.end),
+ };
+ }
+ if (nextSelection) {
+ const previous = input.firstMessageSelectionRef.current;
+ if (
+ nextSelection.start !== previous.start ||
+ nextSelection.end !== previous.end
+ ) {
+ input.voicePendingSelectionEchoesRef.current.push(nextSelection);
+ }
+ input.firstMessageSelectionRef.current = nextSelection;
+ input.setFirstMessageSelection(nextSelection);
+ }
+ input.setFirstMessageDraft(text);
+}
+
+export function changeNewSessionVoiceText(
+ input: NewSessionVoiceSelectionInput,
+ text: string,
+): void {
+ if (text !== input.firstMessageRef.current) {
+ input.voicePendingSelectionEchoesRef.current = [];
+ if (input.voiceStopInFlightRef.current)
+ input.voiceSelectionUserOwnedRef.current = true;
+ }
+ input.setFirstMessageDraft(text);
+}
+
+export function changeNewSessionVoiceSelection(
+ input: NewSessionVoiceSelectionInput,
+ selection: Selection,
+): void {
+ if (
+ !input.voiceRecordingActiveRef.current &&
+ input.voiceStopGestureSelectionGuardRef.current
+ ) {
+ input.voiceStopGestureSelectionGuardRef.current = false;
+ return;
+ }
+ // Native may echo an earlier controlled update after JS publishes the next one,
+ // even after stop resolves. A newer acknowledgement retires coalesced old echoes.
+ const pending = input.voicePendingSelectionEchoesRef.current;
+ const echoIndex = pending.findIndex(
+ (value) => value.start === selection.start && value.end === selection.end,
+ );
+ if (echoIndex >= 0) {
+ pending.splice(0, echoIndex + 1);
+ return;
+ }
+ // Stop marks recording inactive before awaiting ASR/refinement teardown.
+ if (!input.voiceRecordingActiveRef.current) {
+ input.voicePendingSelectionEchoesRef.current = [];
+ const previous = input.firstMessageSelectionRef.current;
+ if (
+ input.voiceStopInFlightRef.current &&
+ (selection.start !== previous.start || selection.end !== previous.end)
+ ) {
+ input.voiceSelectionUserOwnedRef.current = true;
+ }
+ input.firstMessageSelectionRef.current = selection;
+ input.setFirstMessageSelection(selection);
+ }
+}
+
+export interface NewSessionVoiceStopInput {
+ voiceStopInFlightRef: RefObject<boolean>;
+ voiceControllerSessionRef: RefObject<Pick<
+ MobileVoiceControllerSession,
+ "stop"
+ > | null>;
+ voiceRecordingActiveRef: RefObject<boolean>;
+ voiceState: MobileVoiceState;
+ voiceStartupSeqRef: RefObject<number>;
+ voiceStartupInFlightRef: RefObject<boolean>;
+ firstMessageSelectionRef: RefObject<Selection>;
+ firstMessageInputRef: RefObject<{
+ setNativeProps(props: { selection: Selection }): void;
+ } | null>;
+ setVoiceState(state: MobileVoiceState): void;
+ setVoiceError(message: string | null): void;
+ requestAnimationFrame(callback: () => void): unknown;
+ formatRemoteError(error: unknown): string;
+}
+
+/** Preserve the existing stop ownership and final native caret handoff. */
+export async function finishNewSessionVoiceRecording(
+ input: NewSessionVoiceStopInput,
+): Promise<string | null> {
+ if (input.voiceStopInFlightRef.current) return null;
+ const controller = input.voiceControllerSessionRef.current;
+ if (!controller) return null;
+ if (
+ !input.voiceRecordingActiveRef.current &&
+ input.voiceState !== "listening"
+ )
+ return null;
+ input.voiceStartupSeqRef.current += 1;
+ input.voiceStartupInFlightRef.current = false;
+ input.voiceStopInFlightRef.current = true;
+ input.voiceControllerSessionRef.current = null;
+ input.voiceRecordingActiveRef.current = false;
+ input.setVoiceState("submitting");
+ input.setVoiceError(null);
+ try {
+ const latestDraft = await controller.stop();
+ input.setVoiceState("done");
+ input.requestAnimationFrame(() => {
+ input.firstMessageInputRef.current?.setNativeProps({
+ selection: input.firstMessageSelectionRef.current,
+ });
+ });
+ return latestDraft;
+ } catch (err) {
+ input.voiceControllerSessionRef.current = null;
+ input.voiceRecordingActiveRef.current = false;
+ input.setVoiceState("error");
+ input.setVoiceError(input.formatRemoteError(err));
+ return null;
+ } finally {
+ input.voiceStopInFlightRef.current = false;
+ }
+}
+
+export interface NewSessionVoiceComposerInput {
+ platform: string;
+ voiceIsListening: boolean;
+ firstMessage: string;
+ firstMessageSelection: Selection;
+ composerPlaceholder: string;
+ voiceStopGestureSelectionGuardRef: RefObject<boolean>;
+ voicePendingSelectionEchoesRef: RefObject<Selection[]>;
+ finishVoiceRecording(): unknown;
+}
+
+/** Keep the same native input mounted while Android draws the streamed overlay. */
+export function newSessionVoiceComposerProps(
+ input: NewSessionVoiceComposerInput,
+) {
+ return {
+ inputStyle:
+ input.voiceIsListening && input.platform !== "ios"
+ ? input.platform === "android"
+ ? hiddenAndroidVoiceInputStyle
+ : hiddenVoiceInputStyle
+ : undefined,
+ caretHidden: input.voiceIsListening,
+ value: input.firstMessage,
+ placeholder: input.voiceIsListening ? "" : input.composerPlaceholder,
+ selection: input.firstMessageSelection,
+ onKeyPress: () => {
+ input.voicePendingSelectionEchoesRef.current = [];
+ },
+ onPressIn: () => {
+ if (input.voiceIsListening) {
+ input.voiceStopGestureSelectionGuardRef.current = true;
+ setTimeout(() => {
+ input.voiceStopGestureSelectionGuardRef.current = false;
+ }, 0);
+ void input.finishVoiceRecording();
+ } else {
+ // Editing can intentionally return to an old controlled selection value.
+ input.voicePendingSelectionEchoesRef.current = [];
+ }
+ },
+ } satisfies Pick<
+ MobileComposerInputRowProps,
+ | "inputStyle"
+ | "caretHidden"
+ | "value"
+ | "placeholder"
+ | "selection"
+ | "onPressIn"
+ | "onKeyPress"
+ >;
+}
diff --git a/apps/mobile/src/session/prepareNewSessionCreation.ts b/apps/mobile/src/session/prepareNewSessionCreation.ts
new file mode 100644
index 0000000000..84eaf722f9
--- /dev/null
+++ b/apps/mobile/src/session/prepareNewSessionCreation.ts
@@ -0,0 +1,466 @@
+import type { Dispatch, RefObject, SetStateAction } from "react";
+import type { MobileAuthOwnerGeneration } from "@/auth/authOwnerGeneration";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import { formatRemoteError } from "@/device-link/remoteStatus";
+import type { MobileSessionRuntimeOptions } from "./agentCapabilities";
+import type { DurableOutboxRecord } from "./durableOutbox";
+import type { MobileLocalAttachmentUploadCandidate } from "./mobileLocalAttachmentUpload";
+import {
+ getCurrentMobileOutboxRecords,
+ mobileDurableOutbox,
+} from "./mobileDurableOutbox";
+import { outboxCreationRetryIdentity } from "./cancelledCreationDraft";
+import { buildOutboxItem, createOutboxClientId } from "./sessionOutbox";
+import {
+ createNewSessionId,
+ holdNewSessionCreationDraft,
+} from "./newSessionCreation";
+import {
+ compensatePrecreatedWorktree,
+ type NewSessionDraft,
+} from "./newSession";
+import {
+ holdPrecreatedWorktreeRegistration,
+ parseDiscardPrecreatedAck,
+ forgetPendingPrecreatedWorktree,
+ registerPendingPrecreatedWorktree,
+} from "./precreatedWorktreeRecovery";
+import { persistNewSessionCreationDraft } from "./persistNewSessionCreationDraft";
+import {
+ buildWorktreeCreateRequest,
+ parseWorktreeCreateResult,
+ formatWorktreeCreateFailure,
+} from "./newSessionWorktree";
+import type { WorktreeCreateIntentSnapshot } from "./useNewSessionWorktreeSync";
+import type { RemoteSerializedAttachment, RemoteSession } from "./types";
+
+/** Production services are replaceable at the persistence/transport boundary in unit tests. */
+export const newSessionCreationPreparationServices = {
+ getCurrentMobileOutboxRecords,
+ mobileDurableOutbox,
+ outboxCreationRetryIdentity,
+ buildOutboxItem,
+ createNewSessionId,
+ createOutboxClientId,
+ holdNewSessionCreationDraft,
+ holdPrecreatedWorktreeRegistration,
+ persistNewSessionCreationDraft,
+ compensatePrecreatedWorktree,
+ parseDiscardPrecreatedAck,
+ forgetPendingPrecreatedWorktree,
+ registerPendingPrecreatedWorktree,
+ buildWorktreeCreateRequest,
+ parseWorktreeCreateResult,
+ formatRemoteError,
+ formatWorktreeCreateFailure,
+};
+export type NewSessionCreationPreparationServices =
+ typeof newSessionCreationPreparationServices;
+
+export interface NewSessionCreationPreparationInput {
+ effectiveDraft: NewSessionDraft;
+ outboxRecoveryRef: RefObject<DurableOutboxRecord | null>;
+ selectedDeviceId: string;
+ selectedDeviceName: string;
+ authOwnerAtCreate: MobileAuthOwnerGeneration;
+ worktreeAccountId: string;
+ creatingWorktree: boolean;
+ worktreeIntent: WorktreeCreateIntentSnapshot;
+ isCurrentOwner: () => boolean;
+ ensureDeviceAlive: () => boolean;
+ isWorktreeCreateIntentCurrent: (
+ intent: WorktreeCreateIntentSnapshot,
+ ) => boolean;
+ runtimeOptions: Pick<MobileSessionRuntimeOptions, "permissionOptions">;
+ prePlanPermissionModeRef: RefObject<string | null>;
+ planModeCapability: boolean;
+ planModeDraftOn: boolean;
+ sendAttachments: RemoteSerializedAttachment[];
+ attachmentPreviews: Record<string, string>;
+ getUploadedSource: (
+ id: string,
+ ) => MobileLocalAttachmentUploadCandidate | undefined;
+ releaseUploadedSources: (ids: string[]) => void;
+ maker: {
+ getSession: (sessionId: string) => Promise<RemoteSession | null>;
+ worktree: Pick<
+ MobileMakerTransport["worktree"],
+ "suggestName" | "create" | "discardPrecreated"
+ >;
+ };
+ t: (key: string) => string;
+ setError: (error: string) => void;
+ setDraft: Dispatch<SetStateAction<NewSessionDraft>>;
+ resolveWorktreeCreateErrorKey: () => string;
+ onHoldDurableCreation: (release: () => void) => void;
+ onHoldPrecreatedRegistration: (release: () => void) => void;
+}
+
+/**
+ * Save the current form and its attachment bytes before any remote worktree effect.
+ * The caller retains both existing leases until handoff or its finally block.
+ */
+export async function prepareNewSessionCreation(
+ input: NewSessionCreationPreparationInput,
+ services: NewSessionCreationPreparationServices = newSessionCreationPreparationServices,
+) {
+ let {
+ effectiveDraft,
+ outboxRecoveryRef,
+ selectedDeviceId,
+ selectedDeviceName,
+ authOwnerAtCreate,
+ worktreeAccountId,
+ creatingWorktree,
+ worktreeIntent,
+ isCurrentOwner,
+ ensureDeviceAlive,
+ isWorktreeCreateIntentCurrent,
+ runtimeOptions,
+ prePlanPermissionModeRef,
+ planModeCapability,
+ planModeDraftOn,
+ sendAttachments,
+ attachmentPreviews,
+ getUploadedSource,
+ releaseUploadedSources,
+ maker,
+ t,
+ setError,
+ setDraft,
+ resolveWorktreeCreateErrorKey,
+ } = input;
+ const {
+ getCurrentMobileOutboxRecords,
+ mobileDurableOutbox,
+ outboxCreationRetryIdentity,
+ buildOutboxItem,
+ createNewSessionId,
+ createOutboxClientId,
+ holdNewSessionCreationDraft,
+ holdPrecreatedWorktreeRegistration,
+ persistNewSessionCreationDraft,
+ compensatePrecreatedWorktree,
+ parseDiscardPrecreatedAck,
+ forgetPendingPrecreatedWorktree,
+ registerPendingPrecreatedWorktree,
+ buildWorktreeCreateRequest,
+ parseWorktreeCreateResult,
+ formatRemoteError,
+ formatWorktreeCreateFailure,
+ } = services;
+ let releasePrecreatedRegistration: (() => void) | null = null;
+ const previousRecovery = outboxRecoveryRef.current;
+ const recovering = previousRecovery
+ ? getCurrentMobileOutboxRecords().find(
+ (r) =>
+ r.deviceId === previousRecovery.deviceId &&
+ r.item.clientId === previousRecovery.item.clientId &&
+ r.item.sessionId === previousRecovery.item.sessionId,
+ )
+ : null;
+ if (previousRecovery && !recovering) throw new Error("OUTBOX_STALE_WRITE");
+ if (recovering && recovering.deviceId !== selectedDeviceId) {
+ throw new Error(t("session.outbox.recoveryTarget"));
+ }
+ if (
+ recovering?.creation?.cancelled &&
+ previousRecovery?.creation &&
+ effectiveDraft.workingDir === previousRecovery.creation.draft.workingDir &&
+ effectiveDraft.workingDir !== recovering.creation.draft.workingDir
+ ) {
+ // Eligibility and branch preference belong to the old directory. Let the
+ // form probe the restored target before accepting another submission.
+ outboxRecoveryRef.current = recovering;
+ setDraft((current) => ({
+ ...current,
+ workingDir: recovering.creation!.draft.workingDir,
+ }));
+ return;
+ }
+ const recoveryIdentity = recovering
+ ? outboxCreationRetryIdentity(recovering, createNewSessionId)
+ : null;
+ const sessionId = recoveryIdentity?.sessionId ?? createNewSessionId();
+ if (recovering) {
+ // Editing creation parameters is allowed only after the original task is proven absent.
+ let found = false;
+ try {
+ found = !!(await maker.getSession(recovering.item.sessionId));
+ } catch (error) {
+ if (!formatRemoteError(error).includes("NOT_FOUND")) throw error;
+ }
+ if (!isCurrentOwner()) return;
+ if (found) {
+ const latest = getCurrentMobileOutboxRecords().find(
+ (r) =>
+ r.item.clientId === recovering.item.clientId &&
+ r.item.sessionId === recovering.item.sessionId,
+ );
+ if (latest && !latest.prepared)
+ await mobileDurableOutbox.update(latest, {
+ suspended: false,
+ state: "queued",
+ });
+ throw new Error(t("session.outbox.taskAlreadyCreated"));
+ }
+ }
+ const agentKindSnapshot = effectiveDraft.agentKind;
+ const deviceIdSnapshot = selectedDeviceId;
+ const legacyPlanRestore =
+ effectiveDraft.permissionMode === "plan"
+ ? (() => {
+ const fallback =
+ runtimeOptions.permissionOptions.find(
+ (option) => option.id !== "plan",
+ )?.id ?? "ask";
+ const remembered = prePlanPermissionModeRef.current;
+ return remembered && remembered !== "plan" ? remembered : fallback;
+ })()
+ : null;
+ if (!isCurrentOwner()) return;
+ input.onHoldDurableCreation(holdNewSessionCreationDraft(sessionId));
+ const firstMessageClientId =
+ recovering?.item.clientId ?? createOutboxClientId();
+ const useDurableCreation = legacyPlanRestore === null;
+ if (recovering && !useDurableCreation)
+ throw new Error(t("session.outbox.legacyPlanRecovery"));
+ if (useDurableCreation) {
+ const firstRecord: DurableOutboxRecord = {
+ version: 1,
+ accountId: authOwnerAtCreate.accountKey,
+ deviceId: deviceIdSnapshot,
+ ...(recoveryIdentity
+ ? { storageSessionId: recoveryIdentity.storageSessionId }
+ : {}),
+ createdAt: recovering?.createdAt ?? Date.now(),
+ state: recovering ? "failed" : "queued",
+ suspended: !!recovering || creatingWorktree,
+ uploads: [],
+ clearBoundaryMs: null,
+ creation: {
+ draft: effectiveDraft,
+ deviceName: selectedDeviceName,
+ // Replacing a restored draft does not hand it to the background pipeline.
+ // Keep its recovery intent durable until the creation pipeline takes over.
+ ...(recovering ? { editReady: true } : {}),
+ ...(creatingWorktree
+ ? { originalWorkingDir: effectiveDraft.workingDir }
+ : {}),
+ planModeArm: planModeCapability && planModeDraftOn,
+ restorePermissionMode: legacyPlanRestore,
+ },
+ item: buildOutboxItem({
+ clientId: firstMessageClientId,
+ sessionId,
+ text: effectiveDraft.firstMessage,
+ quotesEncoded: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ permissionModeAtSend: effectiveDraft.permissionMode,
+ readyAttachments: sendAttachments,
+ readyPreviews: sendAttachments.map(
+ (a) => attachmentPreviews[a.id] ?? null,
+ ),
+ claimedUploads: [],
+ }),
+ };
+ const saved = await persistNewSessionCreationDraft({
+ record: firstRecord,
+ recovering,
+ getUploadedSource,
+ isCurrent: () => isCurrentOwner() && ensureDeviceAlive(),
+ });
+ if (!saved) return;
+ outboxRecoveryRef.current = saved;
+ if (!isCurrentOwner() || !ensureDeviceAlive()) return;
+ releaseUploadedSources(sendAttachments.map((a) => a.id));
+ }
+ let precreatedWorktree:
+ | {
+ path: string;
+ recoveryKey: string;
+ originalWorkingDir: string;
+ createdAt?: number;
+ }
+ | undefined;
+ // ㉙ 设备切换中止助手(独立 review P1-2/P1-3):检测到设备已切换 → 已产生远端
+ // 副作用(precreated)走 compensatePrecreatedWorktree——**先 discardPrecreated
+ // 获严格 ACK 才 forget**(forget 删唯一账本,未 discard 就删 = 永久孤儿),
+ // ACK 失败/未知保留 ledger 交 recovery;返回 true 供调用方 return。
+ const abortIfDeviceSwitched = async (): Promise<boolean> => {
+ if (ensureDeviceAlive()) return false;
+ if (precreatedWorktree) {
+ const pwt = precreatedWorktree;
+ await compensatePrecreatedWorktree({
+ sessionId,
+ recoveryKey: pwt.recoveryKey,
+ createdAt: pwt.createdAt ?? Date.now(),
+ phase: "precreated",
+ discard: () =>
+ maker.worktree.discardPrecreated({
+ sessionId,
+ recoveryKey: pwt.recoveryKey,
+ }),
+ parseAck: parseDiscardPrecreatedAck,
+ forget: () =>
+ forgetPendingPrecreatedWorktree(worktreeAccountId, {
+ sessionId,
+ recoveryKey: pwt.recoveryKey,
+ createdAt: pwt.createdAt ?? Date.now(),
+ }),
+ release: releasePrecreatedRegistration,
+ });
+ }
+ return true;
+ };
+ // —— worktree 两步流第一步(对齐桌面远程流程 NewMakerDraftRoute:远程没有改已建
+ // 会话 workingDir 的通道,顺序反过来 —— 先同步等工作端建好 worktree 拿路径,再以
+ // 该路径 + 同一预生成 sessionId 走乐观管线)。worktree:create 对同 sessionId 重跑
+ // 不幂等,不能放进管线的重试面 —— 失败(业务 {ok:false} / invoke 抛错)一律留在
+ // 表单展示错误,不建会话(草稿原地保留,与桌面远程失败语义一致)。
+ if (
+ worktreeIntent.applicable &&
+ worktreeIntent.enabled &&
+ worktreeIntent.eligibility.status === "eligible"
+ ) {
+ try {
+ // suggest-name 失败不阻断:走 auto- 兜底名(对齐桌面 :1316)。
+ if (!isCurrentOwner()) return;
+ let suggested: string | null = null;
+ try {
+ suggested = await maker.worktree
+ .suggestName(worktreeIntent.eligibility.baseRepo)
+ .then((result) => result.name);
+ } catch {
+ suggested = null;
+ }
+ if (!isCurrentOwner()) return;
+ if (!ensureDeviceAlive()) return;
+ if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
+ setError(t(resolveWorktreeCreateErrorKey()));
+ return;
+ }
+ const recoveryKey = createNewSessionId();
+ const createdAt = Date.now();
+ releasePrecreatedRegistration =
+ holdPrecreatedWorktreeRegistration(sessionId);
+ input.onHoldPrecreatedRegistration(releasePrecreatedRegistration);
+ // reservation 必须先于远端副作用持久化。首次写盘失败时绝不调用
+ // worktree:create;volatile 镜像只负责阻止本进程继续制造第二个孤儿,
+ // 不能冒充跨进程保证。
+ const reservationRecorded = await registerPendingPrecreatedWorktree(
+ worktreeAccountId,
+ {
+ sessionId,
+ deviceId: selectedDeviceId,
+ recoveryKey,
+ createdAt,
+ phase: "reserved",
+ },
+ );
+ if (!isCurrentOwner()) return;
+ // ㉙ 写盘 reservation 后切设备 → 清掉这份 obligation(reserved 无远端
+ // 目录,不产生孤儿,但会阻塞同设备下次创建的 recovery 直到被回收)。
+ if (!ensureDeviceAlive()) {
+ await forgetPendingPrecreatedWorktree(worktreeAccountId, {
+ sessionId,
+ recoveryKey,
+ createdAt,
+ }).catch(() => undefined);
+ return;
+ }
+ if (!reservationRecorded) {
+ setError(t("session.new.worktreeRecoveryStateFailed"));
+ return;
+ }
+ if (!isCurrentOwner()) return;
+ if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {
+ await forgetPendingPrecreatedWorktree(worktreeAccountId, {
+ sessionId,
+ recoveryKey,
+ createdAt,
+ });
+ setError(t(resolveWorktreeCreateErrorKey()));
+ return;
+ }
+ const createRequest = buildWorktreeCreateRequest({
+ sessionId,
+ eligibility: worktreeIntent.eligibility,
+ sourceBranch: worktreeIntent.sourceBranch,
+ suggestedName: suggested,
+ recoveryKey,
+ });
+ const resp = parseWorktreeCreateResult(
+ await maker.worktree.create(createRequest),
+ createRequest,
+ );
+ if (!isCurrentOwner()) return;
+ if (!resp) {
+ setError(t("session.new.worktreeCleanupPending"));
+ return;
+ }
+ if (!resp.ok) {
+ await forgetPendingPrecreatedWorktree(worktreeAccountId, {
+ sessionId,
+ recoveryKey,
+ createdAt,
+ });
+ if (!isCurrentOwner()) return;
+ setError(formatWorktreeCreateFailure(resp.error));
+ return;
+ }
+ precreatedWorktree = {
+ path: resp.meta.path,
+ recoveryKey,
+ originalWorkingDir: effectiveDraft.workingDir,
+ createdAt,
+ };
+ // ㉙ 远端目录已产生 → 切设备必须走 ledger 补偿(forget + 释放内存持有,
+ // 远端目录留给下次 recovery 对账回收)。
+ if (await abortIfDeviceSwitched()) return;
+ // 回包后尽力把 path 补到账本;即使这次更新失败,首次已确认落盘的
+ // recoveryKey reservation 仍足够让重启后的进程从被控端解析真实路径。
+ await registerPendingPrecreatedWorktree(worktreeAccountId, {
+ sessionId,
+ deviceId: selectedDeviceId,
+ path: precreatedWorktree.path,
+ recoveryKey,
+ createdAt,
+ phase: "precreated",
+ });
+ if (!isCurrentOwner()) return;
+ if (await abortIfDeviceSwitched()) return;
+ effectiveDraft = { ...effectiveDraft, workingDir: resp.meta.path };
+ } catch {
+ if (!isCurrentOwner()) return;
+ // invoke 抛错时无法判断工作端是否已经完成创建;保留 reservation,
+ // 交给当前进程重连或下次冷启动按 recoveryKey 精确对账。
+ setError(t("session.new.worktreeCleanupPending"));
+ return;
+ }
+ }
+ if (useDurableCreation && precreatedWorktree) {
+ const current = outboxRecoveryRef.current;
+ if (!current?.creation || current.item.sessionId !== sessionId)
+ throw new Error("OUTBOX_STALE_WRITE");
+ const updated = await mobileDurableOutbox.update(current, {
+ creation: { ...current.creation, draft: effectiveDraft },
+ suspended: !!current.creation.editReady,
+ });
+ outboxRecoveryRef.current = updated;
+ if (!isCurrentOwner() || !ensureDeviceAlive()) return;
+ }
+ return {
+ effectiveDraft,
+ sessionId,
+ agentKindSnapshot,
+ deviceIdSnapshot,
+ firstMessageClientId,
+ legacyPlanRestore,
+ useDurableCreation,
+ precreatedWorktree,
+ abortIfDeviceSwitched,
+ };
+}
diff --git a/apps/mobile/src/session/useNewSessionWorkspace.ts b/apps/mobile/src/session/useNewSessionWorkspace.ts
new file mode 100644
index 0000000000..68add4dc7f
--- /dev/null
+++ b/apps/mobile/src/session/useNewSessionWorkspace.ts
@@ -0,0 +1,399 @@
+import {
+ useCallback,
+ useEffect,
+ type Dispatch,
+ type RefObject,
+ type SetStateAction,
+} from "react";
+import {
+ pickInitialNewSessionWorkspace,
+ type NewSessionDeviceOption,
+ type NewSessionDraft,
+ type NewSessionStoredPreferences,
+ type buildRecentWorkspaceOptions,
+} from "./newSession";
+import {
+ readNewSessionPreferences,
+ saveNewSessionPreferences,
+} from "./newSessionPreferenceStore";
+import type { drainStashedNewSessionDraft as drainStashedDraft } from "./newSessionCreation";
+import type { restoreNewSessionDraft } from "./newSessionForm";
+
+type RestoredDraftArgs =
+ Parameters<typeof restoreNewSessionDraft> extends [unknown, ...infer Rest]
+ ? Rest
+ : never;
+
+/** Consume only the failed task addressed by this form, then protect it from late defaults. */
+export function useNewSessionStashedDraft(input: {
+ sessionId?: string;
+ deviceId: string;
+ drainStashedNewSessionDraft: typeof drainStashedDraft;
+ restoreCreationDraft: (...args: RestoredDraftArgs) => void;
+ setAttachmentError: (notice: string) => void;
+ onRestoreCollab: (
+ stash: NonNullable<ReturnType<typeof drainStashedDraft>>,
+ ) => void;
+ userTouchedDeviceRef: RefObject<boolean>;
+ setSelectedDeviceId: (id: string) => void;
+ setSelectedDeviceName: (name: string) => void;
+}): void {
+ const {
+ sessionId,
+ deviceId,
+ drainStashedNewSessionDraft,
+ restoreCreationDraft,
+ setAttachmentError,
+ onRestoreCollab,
+ userTouchedDeviceRef,
+ setSelectedDeviceId,
+ setSelectedDeviceName,
+ } = input;
+ useEffect(() => {
+ const stashed = drainStashedNewSessionDraft(sessionId, deviceId);
+ if (!stashed) return;
+ restoreCreationDraft(
+ stashed.draft,
+ [...stashed.attachments],
+ undefined,
+ stashed.deviceId || undefined,
+ );
+ if (stashed.notice) setAttachmentError(stashed.notice);
+ if (stashed.collabDraft && stashed.deviceId) onRestoreCollab(stashed);
+ if (stashed.deviceId) {
+ userTouchedDeviceRef.current = true;
+ setSelectedDeviceId(stashed.deviceId);
+ setSelectedDeviceName(stashed.deviceName || stashed.deviceId);
+ }
+ }, [sessionId, deviceId, restoreCreationDraft]);
+}
+
+type Setter<T> = Dispatch<SetStateAction<T>>;
+interface WorkspaceIdentity {
+ selectedDeviceId: string;
+ initialWorkingDir: string | null;
+ draft: NewSessionDraft;
+ userTouchedWorkspaceRef: RefObject<boolean>;
+ userTouchedDeviceRef: RefObject<boolean>;
+ initialWorkspaceKeyRef: RefObject<string | null>;
+ workingDirPreferenceOverridesRef: RefObject<Record<string, string>>;
+ newSessionPreferences: NewSessionStoredPreferences | null;
+ newSessionPreferencesLoaded: boolean;
+ preferredDefaultDevice: NewSessionDeviceOption | null;
+ setNewSessionPreferences: Setter<NewSessionStoredPreferences | null>;
+ setBrowseOpen: Setter<boolean>;
+ loadBrowsePath: (path: string) => Promise<void>;
+}
+
+export interface NewSessionWorkspacePreferencesInput extends Pick<
+ WorkspaceIdentity,
+ | "initialWorkingDir"
+ | "newSessionPreferences"
+ | "newSessionPreferencesLoaded"
+ | "workingDirPreferenceOverridesRef"
+ | "userTouchedWorkspaceRef"
+ | "userTouchedDeviceRef"
+ | "preferredDefaultDevice"
+ | "setNewSessionPreferences"
+> {
+ setNewSessionPreferencesLoaded: Setter<boolean>;
+ setDraft: Setter<NewSessionDraft>;
+ routeDeviceId: string;
+ routeDeviceName: string;
+ routeDeviceExplicit: boolean;
+ deviceOptions: NewSessionDeviceOption[];
+ appliedDefaultDeviceKeyRef: RefObject<string | null>;
+ setSelectedDeviceId: Setter<string>;
+ setSelectedDeviceName: Setter<string>;
+ setDevicePickerOpen: Setter<boolean>;
+}
+
+/** The initial async preference read never replaces a choice made in this form. */
+export function useNewSessionWorkspacePreferences(
+ input: NewSessionWorkspacePreferencesInput,
+): void {
+ const {
+ newSessionPreferences,
+ setNewSessionPreferences,
+ newSessionPreferencesLoaded,
+ setNewSessionPreferencesLoaded,
+ workingDirPreferenceOverridesRef,
+ initialWorkingDir,
+ userTouchedWorkspaceRef,
+ setDraft,
+ userTouchedDeviceRef,
+ routeDeviceId,
+ routeDeviceName,
+ routeDeviceExplicit,
+ deviceOptions,
+ appliedDefaultDeviceKeyRef,
+ preferredDefaultDevice,
+ setSelectedDeviceId,
+ setSelectedDeviceName,
+ setDevicePickerOpen,
+ } = input;
+ useEffect(() => {
+ let cancelled = false;
+ setNewSessionPreferencesLoaded(false);
+ void readNewSessionPreferences()
+ .then((preferences) => {
+ if (cancelled) return;
+ // 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
+ ? current
+ : { ...current, workspaceKind },
+ );
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setNewSessionPreferencesLoaded(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ useEffect(() => {
+ if (!newSessionPreferencesLoaded) return;
+ if (userTouchedDeviceRef.current) return;
+ const key = [
+ routeDeviceId,
+ routeDeviceName,
+ initialWorkingDir ?? "",
+ routeDeviceExplicit ? "explicit" : "default",
+ newSessionPreferences?.device?.deviceId ?? "",
+ deviceOptions.map((option) => option.deviceId).join(","),
+ ].join("|");
+ if (appliedDefaultDeviceKeyRef.current === key) return;
+ appliedDefaultDeviceKeyRef.current = key;
+ setSelectedDeviceId(preferredDefaultDevice?.deviceId ?? "");
+ setSelectedDeviceName(
+ preferredDefaultDevice?.name ?? preferredDefaultDevice?.deviceId ?? "",
+ );
+ setDevicePickerOpen(false);
+ }, [
+ deviceOptions,
+ initialWorkingDir,
+ newSessionPreferences?.device?.deviceId,
+ newSessionPreferencesLoaded,
+ preferredDefaultDevice?.deviceId,
+ preferredDefaultDevice?.name,
+ routeDeviceExplicit,
+ routeDeviceId,
+ routeDeviceName,
+ ]);
+}
+
+export interface NewSessionWorkspaceActionsInput extends Pick<
+ WorkspaceIdentity,
+ | "draft"
+ | "selectedDeviceId"
+ | "initialWorkingDir"
+ | "setBrowseOpen"
+ | "workingDirPreferenceOverridesRef"
+ | "setNewSessionPreferences"
+ | "userTouchedWorkspaceRef"
+ | "initialWorkspaceKeyRef"
+ | "loadBrowsePath"
+> {
+ patchDraft: (patch: Partial<NewSessionDraft>) => void;
+ setBrowseError: Setter<string | null>;
+ setShowHiddenDirectories: Setter<boolean>;
+ setWorkspacePickerOpen: Setter<boolean>;
+}
+
+/** All explicit workspace choices update the same per-device preference. */
+export function useNewSessionWorkspaceActions(
+ input: NewSessionWorkspaceActionsInput,
+) {
+ const {
+ draft,
+ selectedDeviceId,
+ initialWorkingDir,
+ patchDraft,
+ setBrowseOpen,
+ setBrowseError,
+ setShowHiddenDirectories,
+ workingDirPreferenceOverridesRef,
+ setNewSessionPreferences,
+ userTouchedWorkspaceRef,
+ setWorkspacePickerOpen,
+ initialWorkspaceKeyRef,
+ loadBrowsePath,
+ } = input;
+ const selectWorkingDir = useCallback(
+ (workingDir: string) => {
+ patchDraft({ workingDir });
+ setBrowseOpen(false);
+ setBrowseError(null);
+ setShowHiddenDirectories(false);
+ },
+ [patchDraft],
+ );
+ 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],
+ );
+ 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" });
+ patchDraft({ workspaceKind: "dialogue", workingDir: "" });
+ setWorkspacePickerOpen(false);
+ setBrowseOpen(false);
+ setShowHiddenDirectories(false);
+ }, [patchDraft]);
+ const selectRecentProject = useCallback(
+ (workingDir: string) => {
+ userTouchedWorkspaceRef.current = true;
+ // 显式点选最近项目 = 该设备的目录记忆(#4103);设备未定时只记模式。
+ const remembered = rememberWorkingDirForDevice(workingDir);
+ void saveNewSessionPreferences({
+ workspaceKind: "project",
+ ...(remembered ? { workingDirForDevice: remembered } : {}),
+ });
+ patchDraft({ workspaceKind: "project", workingDir });
+ setWorkspacePickerOpen(false);
+ setBrowseOpen(false);
+ setShowHiddenDirectories(false);
+ },
+ [patchDraft, rememberWorkingDirForDevice],
+ );
+ const openProjectBrowse = useCallback(() => {
+ userTouchedWorkspaceRef.current = true;
+ void saveNewSessionPreferences({ workspaceKind: "project" });
+ patchDraft({ workspaceKind: "project" });
+ setWorkspacePickerOpen(false);
+ setBrowseOpen(true);
+ // 用户显式选择浏览时,消费初始工作区决策,避免 auto-select effect 关掉浏览改选最近项目。
+ initialWorkspaceKeyRef.current = `${selectedDeviceId}:${initialWorkingDir ?? ""}`;
+ void loadBrowsePath(draft.workingDir.trim() || "~");
+ }, [
+ draft.workingDir,
+ loadBrowsePath,
+ patchDraft,
+ selectedDeviceId,
+ initialWorkingDir,
+ ]);
+ return {
+ selectWorkingDir,
+ rememberWorkingDirForDevice,
+ chooseWorkingDir,
+ selectDialogueWorkspace,
+ selectRecentProject,
+ openProjectBrowse,
+ };
+}
+
+export interface NewSessionInitialWorkspaceInput extends Pick<
+ WorkspaceIdentity,
+ | "selectedDeviceId"
+ | "draft"
+ | "newSessionPreferencesLoaded"
+ | "userTouchedDeviceRef"
+ | "preferredDefaultDevice"
+ | "initialWorkingDir"
+ | "initialWorkspaceKeyRef"
+ | "newSessionPreferences"
+ | "setBrowseOpen"
+ | "loadBrowsePath"
+> {
+ recentWorkspaces: ReturnType<typeof buildRecentWorkspaceOptions>;
+ selectWorkingDir: (path: string) => void;
+}
+
+/** Apply the initial directory only after the default computer has settled. */
+export function useNewSessionInitialWorkspace(
+ input: NewSessionInitialWorkspaceInput,
+): void {
+ const {
+ selectedDeviceId,
+ draft,
+ newSessionPreferencesLoaded,
+ userTouchedDeviceRef,
+ preferredDefaultDevice,
+ initialWorkingDir,
+ initialWorkspaceKeyRef,
+ recentWorkspaces,
+ newSessionPreferences,
+ selectWorkingDir,
+ setBrowseOpen,
+ loadBrowsePath,
+ } = input;
+ 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;
+ initialWorkspaceKeyRef.current = key;
+
+ // 先用该设备记住的上次显式选择(#4103),没有再取最近项目首项。
+ const initialWorkspace = pickInitialNewSessionWorkspace(
+ draft.workingDir,
+ recentWorkspaces,
+ newSessionPreferences?.workingDirByDevice?.[selectedDeviceId] ?? null,
+ );
+ if (initialWorkspace) {
+ selectWorkingDir(initialWorkspace);
+ return;
+ }
+
+ setBrowseOpen(true);
+ void loadBrowsePath("~");
+ }, [
+ selectedDeviceId,
+ draft.workspaceKind,
+ draft.workingDir,
+ initialWorkingDir,
+ loadBrowsePath,
+ recentWorkspaces,
+ selectWorkingDir,
+ newSessionPreferencesLoaded,
+ newSessionPreferences?.workingDirByDevice,
+ preferredDefaultDevice?.deviceId,
+ ]);
+}
diff --git a/apps/mobile/src/session/useNewSessionWorktreeSync.ts b/apps/mobile/src/session/useNewSessionWorktreeSync.ts
new file mode 100644
index 0000000000..f503ab6518
--- /dev/null
+++ b/apps/mobile/src/session/useNewSessionWorktreeSync.ts
@@ -0,0 +1,682 @@
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import { withTransientRemoteRetry } from "@/device-link/remoteRetry";
+import {
+ remoteSessionStore,
+ useRemoteNewMakerWorktreePreference,
+} from "./remoteSessionStore";
+import {
+ applyWorktreePreferenceOnHost,
+ classifyWorktreePreferenceSeed,
+ isWorktreeChannelNotAllowedError,
+ shouldBlockNewSessionCreateForWorktree,
+ worktreeEligibilityCaptionKey,
+ type NewSessionWorktreeEligibility,
+} from "./newSessionWorktree";
+import type { NewSessionDraft } from "./newSession";
+
+export interface WorktreePreferenceWriteTransaction {
+ seq: number;
+ deviceId: string;
+ enabled: boolean;
+ revisionAtStart: number;
+ status: "writing" | "reconciling" | "committed";
+}
+
+export interface PendingWorktreePreferenceAuthority {
+ enabled: boolean;
+ revisionAtStart: number;
+}
+
+export interface WorktreeCreateIntentSnapshot {
+ applicable: boolean;
+ enabled: boolean;
+ target: { deviceId: string; workingDir: string };
+ eligibility: NewSessionWorktreeEligibility;
+ sourceBranch: string;
+ branchPreferenceKey: string;
+ branchPreferenceSyncKey: string;
+}
+
+export interface NewSessionWorktreeSyncInput {
+ selectedDeviceId: string;
+ connectionEpoch: number;
+ presenceVersion: number;
+ deviceLinkStatus: string;
+ deviceLinkStatusRef: RefObject<string>;
+ creating: boolean;
+ creatingRef: RefObject<boolean>;
+ draft: Pick<NewSessionDraft, "workspaceKind" | "workingDir" | "agentKind">;
+ maker: Pick<
+ MobileMakerTransport,
+ "getNewMakerDefaults" | "applyNewMakerWorktreePref"
+ >;
+ openLink: (deviceId: string) => Promise<unknown>;
+ worktreeEligibility: NewSessionWorktreeEligibility;
+ worktreeHostSupportsRecoveryKeyDiscard: boolean | null | undefined;
+ worktreeBranchPreferenceSaving: boolean;
+ worktreeBranchPreferenceReady: boolean;
+ worktreeBranchPreferenceReadyKeyRef: RefObject<string | null>;
+ worktreeBranchPreferenceError: boolean;
+ worktreeBranchPreferenceKey: string;
+ worktreeBranchPreferenceSyncKey: string;
+ worktreeBranchPreferenceSyncKeyRef: RefObject<string>;
+ worktreeBranchPreferenceWriteTargetRef: RefObject<string | null>;
+ worktreeBranchPreferenceTransactionRef: RefObject<{
+ key: string;
+ status: "writing" | "unknown" | "committed";
+ } | null>;
+ worktreeBranchTargetRef: RefObject<{ deviceId: string; workingDir: string }>;
+ worktreeEligibilityRef: RefObject<NewSessionWorktreeEligibility>;
+ worktreeSourceBranchRef: RefObject<string>;
+}
+
+/** Keep the draft's explicit choice independent of host preference writes and echoes. */
+export function useNewSessionWorktreeSync({
+ selectedDeviceId,
+ connectionEpoch,
+ presenceVersion,
+ deviceLinkStatus,
+ deviceLinkStatusRef,
+ creating,
+ creatingRef,
+ draft,
+ maker,
+ openLink,
+ worktreeEligibility,
+ worktreeHostSupportsRecoveryKeyDiscard,
+ worktreeBranchPreferenceSaving,
+ worktreeBranchPreferenceReady,
+ worktreeBranchPreferenceReadyKeyRef,
+ worktreeBranchPreferenceError,
+ worktreeBranchPreferenceKey,
+ worktreeBranchPreferenceSyncKey,
+ worktreeBranchPreferenceSyncKeyRef,
+ worktreeBranchPreferenceWriteTargetRef,
+ worktreeBranchPreferenceTransactionRef,
+ worktreeBranchTargetRef,
+ worktreeEligibilityRef,
+ worktreeSourceBranchRef,
+}: NewSessionWorktreeSyncInput) {
+ const worktreePreference =
+ useRemoteNewMakerWorktreePreference(selectedDeviceId);
+
+ // Defaults are advisory. A choice made in this draft wins over later host pushes.
+ const worktreeChoicesRef = useRef(new Map<string, boolean>());
+
+ const [, setWorktreeChoiceVersion] = useState(0);
+
+ const worktreeEnabled =
+ (selectedDeviceId
+ ? worktreeChoicesRef.current.get(selectedDeviceId)
+ : undefined) ?? worktreePreference.enabled;
+
+ const worktreeEnabledRef = useRef(worktreeEnabled);
+
+ worktreeEnabledRef.current = worktreeEnabled;
+
+ const worktreeSeedSeqRef = useRef(0);
+
+ const [worktreeSeedRetryNonce, setWorktreeSeedRetryNonce] = useState(0);
+
+ const worktreePreferenceSyncKeyRef = useRef("");
+
+ const worktreePreferenceWriteSeqRef = useRef(0);
+
+ // Serialize writes of the next default independently of the current draft.
+ const worktreePreferenceWriteTargetRef = useRef<string | null>(null);
+
+ const [
+ worktreePreferenceSavingDeviceId,
+ setWorktreePreferenceSavingDeviceId,
+ ] = useState<string | null>(null);
+
+ const worktreePreferenceTransactionRef =
+ useRef<WorktreePreferenceWriteTransaction | null>(null);
+
+ const worktreePreferenceRenderedRef = useRef({
+ deviceId: selectedDeviceId,
+ enabled: worktreeEnabled,
+ revision: worktreePreference.revision,
+ });
+
+ const worktreePreferenceAuthorityUnknownByDeviceRef = useRef(
+ new Map<string, PendingWorktreePreferenceAuthority>(),
+ );
+
+ const [, setWorktreePreferenceAuthorityVersion] = useState(0);
+
+ const worktreePreferenceSaving =
+ selectedDeviceId != null &&
+ (worktreePreferenceSavingDeviceId === selectedDeviceId ||
+ worktreePreferenceWriteTargetRef.current === selectedDeviceId);
+
+ const worktreePreferenceAwaitingEcho =
+ worktreePreferenceTransactionRef.current?.status === "reconciling";
+
+ const worktreePreferenceSyncKey = selectedDeviceId
+ ? `${selectedDeviceId}\u0000${connectionEpoch}\u0000${presenceVersion}`
+ : "";
+
+ worktreePreferenceSyncKeyRef.current = worktreePreferenceSyncKey;
+
+ const worktreePreferenceAuthorityUnknown =
+ selectedDeviceId != null &&
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.has(selectedDeviceId);
+
+ const worktreeApplicable =
+ draft.workspaceKind === "project" && draft.workingDir.trim().length > 0;
+
+ const worktreeToggleDisabled =
+ creating ||
+ worktreePreferenceSaving ||
+ (worktreeEligibility.status !== "eligible" && !worktreeEnabled);
+
+ // caption 会多占一行、把上方选择器顶起,只在它解释「已勾选但创建被拦」时显示:
+ // 探测中不显示;未勾选时创建不受资格影响,恢复中 / 探测失败也不显示。
+ const worktreeCaptionKey =
+ worktreeEnabled && worktreeEligibility.status !== "probing"
+ ? worktreeEligibilityCaptionKey(worktreeEligibility)
+ : null;
+
+ const worktreeCreateBlocked =
+ shouldBlockNewSessionCreateForWorktree({
+ applicable: worktreeApplicable,
+ enabled: worktreeEnabled,
+ eligibility: worktreeEligibility,
+ // Saving a default does not change the explicit parameters of this request.
+ preferenceSaving: false,
+ }) ||
+ (worktreeEnabled &&
+ (worktreeBranchPreferenceSaving ||
+ (worktreeEligibility.status === "eligible" &&
+ !worktreeBranchPreferenceReady) ||
+ (worktreeBranchPreferenceTransactionRef.current?.key ===
+ worktreeBranchPreferenceKey &&
+ worktreeBranchPreferenceTransactionRef.current.status ===
+ "unknown")));
+
+ const worktreeControlCaptionKey =
+ worktreeCaptionKey ??
+ (worktreePreferenceAuthorityUnknown
+ ? "session.new.worktreeSettingsSyncFailed"
+ : null) ??
+ (worktreeBranchPreferenceError
+ ? "session.new.worktreeBranchSyncFailed"
+ : null);
+
+ const resolveWorktreeCreateErrorKey = useCallback(
+ () =>
+ worktreeEligibilityCaptionKey(worktreeEligibilityRef.current) ??
+ (worktreeBranchPreferenceError
+ ? "session.new.worktreeBranchSyncFailed"
+ : "session.new.worktreeBranchSaving"),
+ [worktreeBranchPreferenceError],
+ );
+
+ useLayoutEffect(() => {
+ worktreePreferenceRenderedRef.current = {
+ deviceId: selectedDeviceId,
+ enabled: worktreePreference.enabled,
+ revision: worktreePreference.revision,
+ };
+ const transaction = worktreePreferenceTransactionRef.current;
+ if (
+ !transaction ||
+ (transaction.status !== "reconciling" &&
+ transaction.status !== "committed") ||
+ transaction.deviceId !== selectedDeviceId ||
+ worktreePreference.enabled !== transaction.enabled ||
+ worktreePreference.revision <= transaction.revisionAtStart
+ )
+ return;
+ worktreePreferenceTransactionRef.current = null;
+ if (worktreePreferenceWriteTargetRef.current === transaction.deviceId) {
+ worktreePreferenceWriteTargetRef.current = null;
+ }
+ setWorktreePreferenceSavingDeviceId(null);
+ }, [
+ selectedDeviceId,
+ worktreePreference.enabled,
+ worktreePreference.revision,
+ worktreePreferenceAwaitingEcho,
+ ]);
+
+ useEffect(() => {
+ if (!selectedDeviceId) return;
+ const transaction = worktreePreferenceTransactionRef.current;
+ if (
+ transaction?.deviceId === selectedDeviceId &&
+ transaction.status === "reconciling" &&
+ worktreePreference.revision > transaction.revisionAtStart &&
+ worktreePreference.enabled !== transaction.enabled
+ ) {
+ // The host echoed a different authoritative value. Do not silently use
+ // it for this Create attempt: release the active spinner, retain the
+ // user's requested value as an unknown obligation, and allow a retry.
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.set(
+ selectedDeviceId,
+ {
+ enabled: transaction.enabled,
+ revisionAtStart: transaction.revisionAtStart,
+ },
+ );
+ worktreePreferenceTransactionRef.current = null;
+ if (worktreePreferenceWriteTargetRef.current === selectedDeviceId) {
+ worktreePreferenceWriteTargetRef.current = null;
+ }
+ setWorktreePreferenceSavingDeviceId(null);
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ }
+ const pending =
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.get(
+ selectedDeviceId,
+ );
+ if (
+ !pending ||
+ worktreePreference.revision <= pending.revisionAtStart ||
+ worktreePreference.enabled !== pending.enabled
+ )
+ return;
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.delete(
+ selectedDeviceId,
+ );
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ }, [
+ selectedDeviceId,
+ worktreePreference.enabled,
+ worktreePreference.revision,
+ worktreePreferenceAwaitingEcho,
+ ]);
+
+ const captureWorktreeCreateIntent =
+ useCallback((): WorktreeCreateIntentSnapshot => {
+ const target = { ...worktreeBranchTargetRef.current };
+ const eligibility = worktreeEligibilityRef.current;
+ const branchPreferenceKey =
+ target.deviceId && eligibility.status === "eligible"
+ ? `${target.deviceId}\u0000${eligibility.baseRepo}`
+ : "";
+ return {
+ applicable:
+ target.deviceId.length > 0 && target.workingDir.trim().length > 0,
+ enabled: worktreeEnabledRef.current,
+ target,
+ eligibility,
+ sourceBranch: worktreeSourceBranchRef.current,
+ branchPreferenceKey,
+ branchPreferenceSyncKey: worktreeBranchPreferenceSyncKeyRef.current,
+ };
+ }, []);
+
+ const isWorktreeCreateIntentCurrent = useCallback(
+ (intent: WorktreeCreateIntentSnapshot): boolean => {
+ if (!intent.applicable) return true;
+ const currentTarget = worktreeBranchTargetRef.current;
+ if (
+ deviceLinkStatusRef.current !== "online" ||
+ currentTarget.deviceId !== intent.target.deviceId ||
+ currentTarget.workingDir.trim() !== intent.target.workingDir.trim()
+ )
+ return false;
+ // ineligible 目标不创建 worktree,无需等偏好同步/就绪——提前返回,
+ // 避免偏好 GET 在途时被下方偏好守卫拦截;与 enabled 无关(2026-08-07 裁决)。
+ // 但快照不能替代实时状态:await 期间同目标可能被重探回 probing/eligible/
+ // detect-failed,旧 ineligible 快照必须复核 live ref 仍为 ineligible 才放行,
+ // 否则回到 fail closed(探测未定不等于确认不合格)。
+ if (!intent.enabled) return true;
+ if (intent.eligibility.status === "ineligible") {
+ return worktreeEligibilityRef.current.status === "ineligible";
+ }
+ // The click captures the displayed choice. Background defaults and persistence
+ // ACKs cannot invalidate an already submitted request.
+ // ineligible 已在前面提前返回,此处只可能是 eligible(2026-08-07 裁决)。
+ if (intent.eligibility.status !== "eligible") return false;
+ // 与 ineligible 快照同理:eligible 快照也必须复核 live 资格仍是同一 repo 的
+ // eligible,await 期间被重探成别的状态或换了 repo 都不能继续建 worktree。
+ const currentEligibility = worktreeEligibilityRef.current;
+ if (
+ currentEligibility.status !== "eligible" ||
+ currentEligibility.baseRepo !== intent.eligibility.baseRepo
+ )
+ return false;
+ const branchTransaction = worktreeBranchPreferenceTransactionRef.current;
+ // A missing branch snapshot may only be a pending read, not host consent
+ // to use the detected branch. Checkbox defaults remain independent.
+ return (
+ worktreeBranchPreferenceReadyKeyRef.current ===
+ intent.branchPreferenceSyncKey &&
+ worktreeBranchPreferenceSyncKeyRef.current ===
+ intent.branchPreferenceSyncKey &&
+ worktreeBranchPreferenceWriteTargetRef.current !==
+ intent.branchPreferenceKey &&
+ !(
+ branchTransaction?.key === intent.branchPreferenceKey &&
+ (branchTransaction.status === "writing" ||
+ branchTransaction.status === "unknown")
+ )
+ );
+ },
+ [],
+ );
+
+ // —— worktree 勾选播种:选中设备后读工作端 get-new-maker-defaults 的 worktreeEnabled
+ // (vendor 无关,agentKind 只是通道入参,经 ref 读当前值,不因切 agent 重播)。
+ // 设备切换 / 链路重连重新播种;老被控端 / 缺字段 / 拉取失败只保留当前镜像。
+ // 全新设备在 store 中没有镜像时本来就是默认未勾选,无需失败路径代替宿主写值。
+ const worktreeSeedAgentKindRef = useRef(draft.agentKind);
+
+ worktreeSeedAgentKindRef.current = draft.agentKind;
+
+ // Read the host capability through a ref: probing a different directory must
+ // not cancel a device-wide defaults request. Old hosts need no missing-field retry.
+ const worktreeHostSupportsRecoveryKeyDiscardRef = useRef(
+ worktreeHostSupportsRecoveryKeyDiscard,
+ );
+
+ worktreeHostSupportsRecoveryKeyDiscardRef.current =
+ worktreeHostSupportsRecoveryKeyDiscard;
+
+ useEffect(() => {
+ const seq = ++worktreeSeedSeqRef.current;
+ const syncKey = worktreePreferenceSyncKey;
+ if (!selectedDeviceId || !syncKey || deviceLinkStatus !== "online")
+ return undefined;
+ const preferenceRevisionAtStart =
+ remoteSessionStore.getNewMakerWorktreePreference(
+ selectedDeviceId,
+ ).revision;
+ let cancelled = false;
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
+ const scheduleRetry = () => {
+ if (retryTimer) return;
+ retryTimer = setTimeout(() => {
+ if (!cancelled) setWorktreeSeedRetryNonce((value) => value + 1);
+ }, 1_500);
+ };
+ // 与上面 detect effect 同款:先建链再拉,包瞬态重试——app 后台恢复时 relay 常在
+ // 重连窗口,裸调会抛 NOT_CONNECTED 并把工作端持久化的勾选偏好静默播种成未勾。
+ void withTransientRemoteRetry(
+ async () => {
+ await openLink(selectedDeviceId);
+ return maker.getNewMakerDefaults(worktreeSeedAgentKindRef.current);
+ },
+ { maxAttempts: 2 },
+ )
+ .then((defaults) => {
+ if (
+ cancelled ||
+ seq !== worktreeSeedSeqRef.current ||
+ worktreePreferenceSyncKeyRef.current !== syncKey
+ )
+ return;
+ // 请求发出后若已收到更晚的 push / 用户点击,旧 pull 不再有覆盖权。
+ if (
+ remoteSessionStore.getNewMakerWorktreePreference(selectedDeviceId)
+ .revision !== preferenceRevisionAtStart
+ )
+ return;
+ const classification = classifyWorktreePreferenceSeed(defaults);
+ if (classification.status === "ready") {
+ // Update only the host mirror. Explicit draft choices remain separate.
+ remoteSessionStore.setNewMakerWorktreePreference(
+ selectedDeviceId,
+ classification.enabled,
+ );
+ return;
+ }
+ if (
+ classification.status === "missing" &&
+ worktreeHostSupportsRecoveryKeyDiscardRef.current === false
+ ) {
+ // Old hosts cannot persist this preference and also lack the recovery
+ // capability marker. A new host can transiently return `{}` before its
+ // renderer cache arrives; keep the last mirror and retry in that case.
+ return;
+ }
+ scheduleRetry();
+ })
+ .catch((error: unknown) => {
+ if (
+ cancelled ||
+ seq !== worktreeSeedSeqRef.current ||
+ worktreePreferenceSyncKeyRef.current !== syncKey
+ )
+ return;
+ if (isWorktreeChannelNotAllowedError(error)) {
+ return;
+ }
+ // A failed defaults read leaves the displayed value usable for creation.
+ scheduleRetry();
+ });
+ return () => {
+ cancelled = true;
+ if (retryTimer) clearTimeout(retryTimer);
+ };
+ }, [
+ connectionEpoch,
+ deviceLinkStatus,
+ presenceVersion,
+ selectedDeviceId,
+ worktreePreferenceSyncKey,
+ worktreeSeedRetryNonce,
+ maker,
+ openLink,
+ ]);
+
+ // Saving the next default is independent of using this draft's explicit choice.
+ // An accepted write may never echo back; release the control after 10 seconds.
+ useEffect(() => {
+ if (!worktreePreferenceSavingDeviceId || !worktreePreferenceAwaitingEcho)
+ return;
+ const transaction = worktreePreferenceTransactionRef.current;
+ const timer = setTimeout(() => {
+ if (
+ !transaction ||
+ worktreePreferenceTransactionRef.current !== transaction
+ )
+ return;
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.set(
+ transaction.deviceId,
+ {
+ enabled: transaction.enabled,
+ revisionAtStart: transaction.revisionAtStart,
+ },
+ );
+ worktreePreferenceTransactionRef.current = null;
+ worktreePreferenceWriteTargetRef.current = null;
+ setWorktreePreferenceSavingDeviceId(null);
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ }, 10_000);
+ return () => clearTimeout(timer);
+ }, [worktreePreferenceSavingDeviceId, worktreePreferenceAwaitingEcho]);
+
+ // 用户显式点击开关:先写工作端,工作端接受后才更新手机内存镜像。
+ // 资格不满足导致的禁用不会走到这里 —— 环境因素不抹掉用户偏好;
+ // 写入失败也不在手机上制造一份假的持久状态。
+ const toggleWorktree = useCallback(() => {
+ if (
+ creatingRef.current ||
+ !selectedDeviceId ||
+ worktreePreferenceSaving ||
+ worktreePreferenceWriteTargetRef.current === selectedDeviceId
+ )
+ return;
+ const targetDeviceId = selectedDeviceId;
+ const next = !worktreeEnabledRef.current;
+ worktreeChoicesRef.current.set(targetDeviceId, next);
+ worktreeEnabledRef.current = next;
+ setWorktreeChoiceVersion((value) => value + 1);
+ // 播种在途回包不得覆盖用户显式选择(seq 作废旧回包)。
+ worktreeSeedSeqRef.current += 1;
+ const preferenceRevisionAtStart =
+ remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId).revision;
+ const writeSeq = worktreePreferenceWriteSeqRef.current + 1;
+ worktreePreferenceWriteSeqRef.current = writeSeq;
+ if (
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.delete(
+ targetDeviceId,
+ )
+ ) {
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ }
+ const transaction: WorktreePreferenceWriteTransaction = {
+ seq: writeSeq,
+ deviceId: targetDeviceId,
+ enabled: next,
+ revisionAtStart: preferenceRevisionAtStart,
+ status: "writing",
+ };
+ // Switching devices may replace a write that is still awaiting ACK/echo.
+ // Preserve its uncertainty in the existing per-device reconciliation map.
+ const previousTransaction = worktreePreferenceTransactionRef.current;
+ if (
+ previousTransaction &&
+ previousTransaction.deviceId !== targetDeviceId
+ ) {
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.set(
+ previousTransaction.deviceId,
+ {
+ enabled: previousTransaction.enabled,
+ revisionAtStart: previousTransaction.revisionAtStart,
+ },
+ );
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ }
+ worktreePreferenceTransactionRef.current = transaction;
+ // Serialize preference writes; Create/Goal use the synchronous draft choice above.
+ worktreePreferenceWriteTargetRef.current = targetDeviceId;
+ setWorktreePreferenceSavingDeviceId(targetDeviceId);
+ const releaseWrite = () => {
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ if (worktreePreferenceTransactionRef.current?.seq === writeSeq) {
+ worktreePreferenceTransactionRef.current = null;
+ }
+ if (worktreePreferenceWriteTargetRef.current === targetDeviceId) {
+ worktreePreferenceWriteTargetRef.current = null;
+ }
+ setWorktreePreferenceSavingDeviceId(null);
+ };
+ const markAuthorityUnknown = () => {
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ worktreePreferenceAuthorityUnknownByDeviceRef.current.set(
+ targetDeviceId,
+ {
+ enabled: next,
+ revisionAtStart: preferenceRevisionAtStart,
+ },
+ );
+ setWorktreePreferenceAuthorityVersion((value) => value + 1);
+ releaseWrite();
+ setWorktreeSeedRetryNonce((value) => value + 1);
+ };
+ const armCommittedRender = () => {
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ transaction.status = "committed";
+ const rendered = worktreePreferenceRenderedRef.current;
+ if (
+ rendered.deviceId === targetDeviceId &&
+ rendered.enabled === next &&
+ rendered.revision > preferenceRevisionAtStart
+ )
+ releaseWrite();
+ };
+ void (async () => {
+ try {
+ const outcome = await applyWorktreePreferenceOnHost({
+ enabled: next,
+ apply: maker.applyNewMakerWorktreePref,
+ // unsupported 可能是“有偏好写穿、缺安全 worktree 能力”,也可能是最老端
+ // 连偏好 channel 都没有:先写 host;只有后者且用户明确点 OFF 时才清手机
+ // 保留的旧 ON 镜像。断连/超时不降级,仍保留 ON + fail closed。
+ allowUnsupportedDisableFallback:
+ !next && worktreeEligibility.status === "unsupported",
+ mirror: (enabled) => {
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ const current =
+ remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId);
+ if (current.revision === preferenceRevisionAtStart) {
+ remoteSessionStore.setNewMakerWorktreePreference(
+ targetDeviceId,
+ enabled,
+ );
+ }
+ const accepted =
+ remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId);
+ if (
+ accepted.revision > preferenceRevisionAtStart &&
+ accepted.enabled === enabled
+ ) {
+ armCommittedRender();
+ } else {
+ markAuthorityUnknown();
+ }
+ },
+ });
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ if (outcome === "accepted") {
+ // Main acknowledged the broadcast; track persistence separately from creation.
+ transaction.status = "reconciling";
+ setWorktreeSeedRetryNonce((value) => value + 1);
+ }
+ } catch (error) {
+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;
+ if (isWorktreeChannelNotAllowedError(error)) {
+ // Explicit old-channel rejection proves this ON request did not
+ // commit. Keep the rendered value and let the user continue.
+ releaseWrite();
+ return;
+ }
+ // Lost ACK / disconnect may have committed remotely. Reconcile the default
+ // via push/GET, while the explicit draft choice remains usable.
+ markAuthorityUnknown();
+ }
+ })();
+ }, [
+ maker,
+ selectedDeviceId,
+ worktreeEnabled,
+ worktreePreferenceSaving,
+ worktreeEligibility.status,
+ ]);
+ const prepareWorktreeCreateIntent = useCallback(
+ (
+ onError: (key: string) => void,
+ ): WorktreeCreateIntentSnapshot | undefined => {
+ const intent = captureWorktreeCreateIntent();
+ if (!isWorktreeCreateIntentCurrent(intent)) {
+ onError(resolveWorktreeCreateErrorKey());
+ return undefined;
+ }
+ return intent;
+ },
+ [
+ captureWorktreeCreateIntent,
+ isWorktreeCreateIntentCurrent,
+ resolveWorktreeCreateErrorKey,
+ ],
+ );
+
+ return {
+ worktreeEnabled,
+ worktreeApplicable,
+ worktreeToggleDisabled,
+ worktreeCreateBlocked,
+ worktreeCaptionKey,
+ worktreeControlCaptionKey,
+ resolveWorktreeCreateErrorKey,
+ captureWorktreeCreateIntent,
+ isWorktreeCreateIntentCurrent,
+ toggleWorktree,
+ worktreePreferenceSaving,
+ worktreePreferenceAuthorityUnknown,
+ prepareWorktreeCreateIntent,
+ };
+}
diff --git a/docs/dev-rules/README.md b/docs/dev-rules/README.md
index 843c842a68..2e6c0e6e98 100644
--- a/docs/dev-rules/README.md
+++ b/docs/dev-rules/README.md
@@ -13,7 +13,10 @@
## 当前文档
-- [`repo-map.md`](repo-map.md):仓库地图——apps、packages 与顶层目录的定位导航。
+- 模块工作入口:[Desktop](../../apps/desktop/AGENTS.md)、[Mobile](../../apps/mobile/AGENTS.md)、
+ [maker-core](../../packages/maker-core/AGENTS.md);这里只索引模块触发条件,专题正文不重复维护。
+- [`repo-map.md`](repo-map.md):仓库地图——目录职责,以及发送、权限、恢复、默认模型和手机新建任务的生产入口、共享判据与测试。
+- [`session-regressions.md`](session-regressions.md):已发生过的任务体验回归、现有测试入口与运行命令。
- [`environment-setup.md`](environment-setup.md):公共开发环境、依赖安装与 submodule
准备。
- [`model-catalog-maintenance.md`](model-catalog-maintenance.md):模型配置与下发统一入口——架构图、字段职责、覆盖顺序、修改位置、代码导航与发布验收。
diff --git a/docs/dev-rules/environment-setup.md b/docs/dev-rules/environment-setup.md
index 2628e9ee77..2676e32e60 100644
--- a/docs/dev-rules/environment-setup.md
+++ b/docs/dev-rules/environment-setup.md
@@ -42,6 +42,12 @@ correctly`。`pnpm test:unit` 等 workspace 测试开跑前也会只读检查一
在该 worktree 内重新运行 `pnpm install`;不要加 `--ignore-scripts`,上述补装都在安装
脚本里完成。
+Mobile 的 Global / CN 开发与打包只需仓内公开端点清单,不要求本机存在
+`config/endpoint.dev.json`。Metro 在这两个区域将私有 dev 清单排除出依赖图;不能靠从
+另一个 checkout 复制私有配置来修复新 worktree。只有显式选择 `--region=dev` 时才需要
+按 `config/endpoint.dev.json.example` 准备该文件,缺失时保持明确失败,不切换区域或端点。
+模拟器与运行源码身份检查使用 [Mobile 开发入口](mobile-development.md#日常模拟器入口)。
+
Cindy Make 的设置入口和指令前置弹窗共用源码准备流程:切到 `cindy-personal` 后,
按锁文件预热包含开发依赖的 pnpm store 缓存,成功后才标记源码就绪。预热使用
`pnpm fetch --frozen-lockfile --prefer-offline --prod=false --ignore-scripts
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index a562c3c6b9..0675a7a39b 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -65,6 +65,23 @@ pnpm mobile:sim:start -- --region=cn
`--region=cn`,或使用名称已明确限定区域的 `mobile:sim:start:cn`。发布构建继续要求显式
指定 region。
+Global / CN 在全新 worktree 中不需要 `config/endpoint.dev.json`;Metro 会将该私有清单
+排除出它们的 bundle,即使本机已有该文件也不打入。显式 `--region=dev` 仍读取 dev 正本,
+缺失或非法时应修复配置,不得回落到 Global / CN,也不要从其他 checkout 复制私有配置。
+
+复现或验收时,将现有身份检查保存在该任务的产物目录。先安装依赖、创建产物目录,再把
+下例 UDID 和区域换成实际目标;直接调用同一脚本,避免 pnpm 与依赖检查日志混进 JSON:
+
+```bash
+node apps/mobile/scripts/sim-whoami.mjs --region=global --udid <UDID> --json > outputs/<任务>/mobile-identity.json
+```
+
+JSON 已包含 `worktree` / `expectedSource`、`region` / `bundleId`、目标设备 UDID、安装版本、
+`native` 指纹检查和 `metros` 运行归属,无需再维护一份手工版本台账。保留退出码:非零或
+`healthy: false` 表示身份链未通过;`healthy: true` 仍不证明 App 已加载新 bundle,
+`pageVerified: false` 明确保留这个边界。页面/bundle 验证与截图按模拟器调试手册另外完成,
+证据放在同一任务目录。
+
不要用临时 Metro、端口探测或手工修改 `.env` 代替这些脚本。多 worktree、原生构建、
登录态和日志排查见 `apps/mobile/docs/simulator-debugging.md`。
@@ -295,14 +312,14 @@ prebuild 时将 Expo 模板默认的 `proguard-android.txt` 换成
SDK 规则随依赖一起进入应用的最终 R8 配置,不在应用侧重复保留全部依赖:
-| Android SDK / 桥接 | 保留规则来源与边界 |
-| --- | --- |
-| React Native、Reanimated / Worklets | 使用依赖自带的 consumer rules,保留 JNI / TurboModule / Fabric 入口。 |
-| Expo 原生模块 | 使用 `expo-modules-core` 的 consumer rules,保留模块构造与 `definition()`、Record、视图等动态入口。自定义模块的函数名通过 `ModuleDefinition` 字符串注册。 |
-| 微信 OpenSDK 6.8.38 | Maven AAR 自带 `com.tencent.mm.opensdk` / `com.tencent.wxop` 规则;微信回调 Activity 由 config plugin 写入 manifest,由 Android 构建规则保留。 |
-| TapSDK 4.10.5 | `modules/xdt-tapdb/android/consumer-rules.pro` 按[官方接入要求](https://developer.taptap.io/docs/sdk/access/quickstart/#android-code-obfuscation)保留 `com.taptap` / `com.tapsdk`,覆盖服务发现及反射调用。 |
-| ONNX Runtime Android 1.30.0 | `modules/cindy-speaker-onnx/android/consumer-rules.pro` 保留 `ai.onnxruntime` 的类与成员,覆盖 JNI 按原名查找的 `TensorInfo` 等类型及构造方法。声纹录入与过滤须用开启 R8 的 release 包验证,mock 原生桥的 JS 单测不能替代。 |
-| Nimbus JOSE JWT 10.9.1 | 远控凭证模块直接调用 JOSE API,协议 JSON 使用显式键名的 `JSONObject` / Map,不依赖业务类字段名反射序列化。`cindy-remote-credentials/android/consumer-rules.pro` 仅忽略未启用的 XC20P 算法所需的可选 Tink 类;当前协议创建和接收均限制为 `ECDH-ES + A256GCM`。若扩展算法,须重新核对可选依赖。 |
+| Android SDK / 桥接 | 保留规则来源与边界 |
+| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| React Native、Reanimated / Worklets | 使用依赖自带的 consumer rules,保留 JNI / TurboModule / Fabric 入口。 |
+| Expo 原生模块 | 使用 `expo-modules-core` 的 consumer rules,保留模块构造与 `definition()`、Record、视图等动态入口。自定义模块的函数名通过 `ModuleDefinition` 字符串注册。 |
+| 微信 OpenSDK 6.8.38 | Maven AAR 自带 `com.tencent.mm.opensdk` / `com.tencent.wxop` 规则;微信回调 Activity 由 config plugin 写入 manifest,由 Android 构建规则保留。 |
+| TapSDK 4.10.5 | `modules/xdt-tapdb/android/consumer-rules.pro` 按[官方接入要求](https://developer.taptap.io/docs/sdk/access/quickstart/#android-code-obfuscation)保留 `com.taptap` / `com.tapsdk`,覆盖服务发现及反射调用。 |
+| ONNX Runtime Android 1.30.0 | `modules/cindy-speaker-onnx/android/consumer-rules.pro` 保留 `ai.onnxruntime` 的类与成员,覆盖 JNI 按原名查找的 `TensorInfo` 等类型及构造方法。声纹录入与过滤须用开启 R8 的 release 包验证,mock 原生桥的 JS 单测不能替代。 |
+| Nimbus JOSE JWT 10.9.1 | 远控凭证模块直接调用 JOSE API,协议 JSON 使用显式键名的 `JSONObject` / Map,不依赖业务类字段名反射序列化。`cindy-remote-credentials/android/consumer-rules.pro` 仅忽略未启用的 XC20P 算法所需的可选 Tink 类;当前协议创建和接收均限制为 `ECDH-ES + A256GCM`。若扩展算法,须重新核对可选依赖。 |
升级 SDK 时核对其 AAR/JAR 的 consumer rules、应用的最终 `configuration.txt` 和 release
运行结果。共享的 Expo 配置也可能改变 iOS 指纹,冷更范围以指纹比对为准。
diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.md
index 3618bc97c3..8da22bf3f0 100644
--- a/docs/dev-rules/repo-map.md
+++ b/docs/dev-rules/repo-map.md
@@ -3,17 +3,44 @@
> **读取时机**:首次接触本仓、需要定位某个功能的代码位置、或新增代码/依赖前判断
> 应该放进哪个模块时
-本文只做**定位导航**:每个目录一句话说明"它是干什么的、谁在用它"。事实源是各目录
-的 `package.json` 与 README;发现本文与代码不一致时,以代码为准并顺手修正本文。
+本文只做**定位导航**:先按用户行为找生产入口、共享判据和测试,再按目录判断代码归属。
+事实源是各目录的源码、`package.json` 与 README;发现本文与代码不一致时,以代码为准并顺手修正本文。
依赖方向与解耦约束见 [`architecture-invariants.md`](architecture-invariants.md)。
+## 按用户行为定位
+
+模块约束从 [Desktop](../../apps/desktop/AGENTS.md)、[Mobile](../../apps/mobile/AGENTS.md)、
+[maker-core](../../packages/maker-core/AGENTS.md) 进入;下表记录现有入口,不另建任务生命周期框架。
+`register.ts` 仍负责部分宿主接线,按表中的函数/IPC 名定位即可,不必从头阅读。
+
+| 用户行为 | 生产入口与共享判据 | 从哪些测试开始 |
+| --- | --- | --- |
+| 发送、排队、插话、停止后继续 | [AgentInputCoordinator](../../apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts) 持有输入事务;[register.ts](../../apps/desktop/src/main/maker-ipc/register.ts) 的 `sendToSessionInternal` 接宿主发送;[agentInputQueue](../../apps/desktop/src/shared/agentInputQueue.ts) 定义队列契约。个人 IM / 官方 hook 的调用方账本见 [IM 轮次流程](im-turn-flow.md)。 | [coordinator](../../apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts)、[队列契约](../../apps/desktop/src/main/__tests__/agentInputQueue.test.ts) |
+| 普通任务、伙伴与群任务切换权限 | [register.ts](../../apps/desktop/src/main/maker-ipc/register.ts) 的 `SET_PERMISSION_MODE` 与 [sessionPermissionChange](../../apps/desktop/src/main/maker-ipc/sessionPermissionChange.ts) 处理运行期变更;未加载运行时的持久化走 [sessionPermissionPersistence](../../apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts),伙伴专线同步走 [botPermissionSync](../../apps/desktop/src/main/maker-ipc/botPermissionSync.ts)。[permissionMode](../../packages/maker-shared/src/permissionMode.ts) 统一客户端的未知档位与 Full access 确认判据;实际执行权限仍由宿主/引擎决定。 | [权限持久化与专线同步](../../apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts)、[引擎控制](../../packages/maker-core/src/session-control.test.ts)、[跨端权限判据](../../packages/maker-shared/src/__tests__/permissionMode.test.ts) |
+| 重启后发现中断任务、运行中断后续跑 | 启动候选由 [sessionActiveTurn](../../apps/desktop/src/main/localDb/sessionActiveTurn.ts) 判定,[interruptedResumeCandidates](../../apps/desktop/src/main/localDb/interruptedResumeCandidates.ts) 补展示信息;运行期自动续跑由 [interruptedTurnAutoResume](../../apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts) 分类,再回输入协调器。两者不是同一触发条件。 | [启动中断判据](../../apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts)、[启动恢复对话框](../../apps/desktop/src/renderer/features/cc-agent/__tests__/InterruptedTasksResumeDialog.test.tsx)、[自动续跑判据](../../apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts) |
+| 新任务与伙伴选择默认模型 | Desktop 的 [newMakerDefaultTuple](../../apps/desktop/src/shared/newMakerDefaultTuple.ts) 选择默认组合;[botDefaultModelChain](../../apps/desktop/src/shared/botDefaultModelChain.ts) 复用推荐,但伙伴设置与新任务输入框选择独立。Mobile 的 [useNewSessionDefaultSelection](../../apps/mobile/src/session/useNewSessionDefaultSelection.ts) 调用 [newSession](../../apps/mobile/src/session/newSession.ts) 中的 `resolveNewSessionAutoDefault`,被控端默认与缓存由 [useNewSessionHostDefaults](../../apps/mobile/src/session/useNewSessionHostDefaults.ts) 提供。目录来源与覆盖顺序见[模型配置与下发](model-catalog-maintenance.md)。 | [默认组合](../../apps/desktop/src/renderer/lib/__tests__/newMakerDefaultTuple.test.ts)、[伙伴默认](../../apps/desktop/src/shared/__tests__/botDefaultModelChain.test.ts)、[手机默认与缓存](../../apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx) |
+| 手机新建任务、创建中继续输入、失败回编辑 | [new.tsx](../../apps/mobile/app/sessions/new.tsx) 组装页面;[prepareNewSessionCreation](../../apps/mobile/src/session/prepareNewSessionCreation.ts) 先保存草稿与附件,再预建 worktree;[newSessionCreation](../../apps/mobile/src/session/newSessionCreation.ts) 持有跨页面的乐观创建管线;[useNewSessionDraftRecovery](../../apps/mobile/src/session/useNewSessionDraftRecovery.ts) 恢复草稿。 | [乐观创建](../../apps/mobile/src/__tests__/newSessionCreation.test.ts)、[真实恢复 hook](../../apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx)、[草稿持久化](../../apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts) |
+
+同一行为涉及普通任务、伙伴、群、调度、本机与远程入口时,从公共入口反查调用方,保留产品规则明确的差异。
+手机新建页的[表单编辑与恢复](../../apps/mobile/src/session/newSessionForm.ts)、
+[工作区选择](../../apps/mobile/src/session/useNewSessionWorkspace.ts)、
+[worktree 偏好同步](../../apps/mobile/src/session/useNewSessionWorktreeSync.ts)、
+[语音与光标](../../apps/mobile/src/session/newSessionVoiceInput.ts)、
+[模型运行选项校准](../../apps/mobile/src/session/newSessionRuntimeReconciliation.ts)和
+[待发消息的会话适配](../../apps/mobile/src/session/mobileOutboxSessionAdapter.ts)可直接测试;
+创建前的附件与草稿写盘复用 [persistNewSessionCreationDraft](../../apps/mobile/src/session/persistNewSessionCreationDraft.ts)。
+最小草稿、附件与异步夹具复用 [fixtures/newSession](../../apps/mobile/src/__tests__/fixtures/newSession.ts)。
+测试优先直接 import 生产模块或挂载真实 hook;价值门槛与源码契约的适用范围见
+[工程约定 §3.2](engineering-conventions.md#32-新增测试的价值门槛),选测入口见[开发流程](development-workflow.md)。
+创建中继续输入、离线历史与后台失败等已发生过的回归,见[任务回归场景](session-regressions.md)。
+
## 顶层结构
| 路径 | 说明 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `apps/` | 终端产品(desktop、mobile)与随包分发的二进制资产 |
| `packages/` | 客户端共享能力包(与 render/main 解耦,详见下表) |
-| `config/` | 运行期端点清单(`endpoint.json` / `endpoint.dev.json` / `endpoint.global.json`:auth、device-link 等线上 base URL) |
+| `config/` | 区域端点清单(CN / Global 的公共配置与本地 dev 模板);新 worktree 的本地配置准备见[环境安装](environment-setup.md) |
| `scripts/` | 仓库级工程脚本:dev 启动包装、agent 二进制拉取(`ensure-agent-binaries.mjs`)、i18n/endpoint/文档等校验 guard、worktree 管理 |
| `tools/` | claude/codex/ripgrep/pi 四个 Desktop runtime 的版本 pin(`latest.json`)与更新器(`update.mjs`) |
| `docs/` | 规则文档:`dev-rules/`(工程)、`product-rules/`(产品)、`design-rules/`(设计入口)、`legal/` 等 |
@@ -24,7 +51,7 @@
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/desktop` | Cindy 桌面客户端(Electron + Vite),源码分 `main/`(主进程:业务逻辑、maker-host/maker-ipc、localDb、device-link、mcp-integrations、cindy-brain 等)、`renderer/`(纯渲染 UI:features、panels、themes、i18n 等)、`preload/`(最小桥接层)、`shared/`(主/渲染共享类型与常量);SQLite migration 在 `apps/desktop/drizzle/` |
| `apps/mobile` | Cindy 手机客户端(Expo / React Native):同账号登录、发现并远程控制桌面设备、镜像会话 |
-| `apps/claude-code-bin`、`apps/codex-bin`、`apps/ripgrep-bin` | 随桌面端分发的预编译 CLI 二进制(按平台分目录)。不是构建包、不进 git 历史;版本由 `tools/<kind>/latest.json` pin,`pnpm install` postinstall 按需下载 |
+| `apps/claude-code-bin`、`apps/codex-bin`、`apps/ripgrep-bin`、`apps/pi-bin` | 随桌面端分发的预编译 CLI 二进制(按平台分目录)。不是构建包、不进 git 历史;版本由 `tools/<kind>/latest.json` pin,`pnpm install` postinstall 按需下载 |
| `apps/android-platform-tools-bin` | Android platform-tools(adb 等)二进制,当前仅 win32-x64,用于连接安卓设备 |
## packages/
diff --git a/docs/dev-rules/session-regressions.md b/docs/dev-rules/session-regressions.md
new file mode 100644
index 0000000000..adbdbfa7ad
--- /dev/null
+++ b/docs/dev-rules/session-regressions.md
@@ -0,0 +1,44 @@
+# 任务体验回归入口
+
+> 修改任务创建、发送、恢复、归档、权限或默认模型时,先从对应行找到现有测试。
+> 代码位置和共用入口见[仓库地图](repo-map.md),测试价值与分层遵循[工程约定](engineering-conventions.md#32-新增测试的价值门槛)。
+
+这份索引保存已反复遇到的用户场景与验证入口,不另建状态机或测试运行器。修改共同入口时反查普通任务、伙伴、群、调度、本机和远程调用方;只检查本次行为影响的入口,保留产品明确要求的差异。
+
+| 场景 | 要保住的行为 | 现有回归入口 |
+| --- | --- | --- |
+| 新任务创建中继续输入,创建或发送失败后回编辑 | 第一条消息立即出现;后续文字和附件留在草稿;取消、删除和迟到的回复不复活任务 | [newSessionCreation](../../apps/mobile/src/__tests__/newSessionCreation.test.ts)、[真实恢复 hook](../../apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx)、[创建草稿落盘](../../apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts) |
+| 断线时读历史,恢复连接后补齐 | 保留已显示的历史;遗漏 push 只标记需要补读;旧查询不能覆盖新的正文和删除状态 | [remoteSessionStore](../../apps/mobile/src/__tests__/remoteSessionStore.test.ts) 中 `requests history reconciliation after a dropped push without clearing cached messages` 与消息 authority 场景;[durableOutbox](../../apps/mobile/src/__tests__/durableOutbox.test.ts) 验证重复投递和账号归属 |
+| 归档先收起,后台未成功时恢复 | 预览阶段只隐藏列表行,详情元数据与正文保留;结束旧预览不影响新操作,不复活已删除任务 | [remoteSessionStore](../../apps/mobile/src/__tests__/remoteSessionStore.test.ts) 的两个 `archive preview` 场景;覆盖 store 行为,实际错误提示与滑动动画还需页面验收 |
+| 普通任务与伙伴运行中切换权限 | 以 Host 接受并持久化后的状态为准;失败不假报成功、不发旧状态回滚;确认规则共用 | [sessionPermissionPersistence](../../apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts)、[botPermissionSwitch](../../apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts)、[permissionMode](../../packages/maker-shared/src/__tests__/permissionMode.test.ts) |
+| 重启后发现中断任务、运行中断后续跑 | 启动候选与运行期续跑分别验证;已结束、已清空、已删除等边界不能误续跑 | [sessionActiveTurn](../../apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts)、[interruptedTurnAutoResume](../../apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts) |
+| 供应商与模型缓存先显示,更新不覆盖手选 | 初值来自现有默认与缓存;任务内手动选择后不被后台默认值重置;伙伴默认与新任务选择独立 | [newSessionHostDefaults](../../apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx)、[newMakerDefaultTuple](../../apps/desktop/src/renderer/lib/__tests__/newMakerDefaultTuple.test.ts)、[botDefaultModelChain](../../apps/desktop/src/shared/__tests__/botDefaultModelChain.test.ts) |
+| 新 worktree 没有个人开发配置 | Global/CN 实际打包不要求或带入私有 dev 配置;显式 dev 仍要求自己的配置 | [envBundleTransform](../../apps/mobile/src/__tests__/envBundleTransform.test.ts),覆盖 Expo 转换、Metro 依赖收集和解析 |
+
+## 按改动选测
+
+在仓库根执行,默认使用既有相关选测:
+
+```sh
+pnpm test:unit:related
+```
+
+需要复现具体场景时,直接运行对应文件,不依靠提取源码片段来模拟页面。以下是手机创建/历史/归档的入口;可以按改动缩小到其中一两个文件:
+
+```sh
+pnpm --filter mobile exec vitest run src/__tests__/newSessionCreation.test.ts src/__tests__/useNewSessionDraftRecovery.test.tsx src/__tests__/newSessionCreationPersistence.test.ts src/__tests__/remoteSessionStore.test.ts src/__tests__/durableOutbox.test.ts
+```
+
+桌面权限入口示例:
+
+```sh
+pnpm --filter desktop exec vitest run src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts
+```
+
+移动端提取 hook 或修改参数类型后补 `pnpm --filter mobile typecheck`。测试移动到新模块时,应保留静态生产依赖,让关联选测能选中它;共享夹具用[现有 typed fixtures](../../apps/mobile/src/__tests__/fixtures/newSession.ts),不再复制一整套页面变量。
+
+## 页面验证记录
+
+单测验证数据和控制流程;用户可见的乐观显示、滚动、导航、滑动和错误提示仍按对应 [Desktop](desktop-development.md)/[Mobile](mobile-development.md) 规则验收。记录实际工作区、commit、运行中的版本身份、操作、可见结果和截图/日志位置,避免“代码通过了”被误读成“这台设备上的页面已验证”。
+
+遇到新的复现,优先补在表中已有行为测试里,并写出触发条件和用户结果;只有出现新的业务边界时再建模块。本文只链接测试,不复制测试断言,不维护通过次数或临时任务状态。
diff --git a/package.json b/package.json
index a1c842abb4..5ffc07a4f7 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs scripts/__tests__/check-test-hygiene.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs",
+ "test:runner": "node --test scripts/__tests__/repo-worktrees.test.mjs scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs scripts/__tests__/check-test-hygiene.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs",
"test:workspaces": "node scripts/test-workspaces.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",
diff --git a/packages/maker-core/AGENTS.md b/packages/maker-core/AGENTS.md
new file mode 100644
index 0000000000..eee0c47927
--- /dev/null
+++ b/packages/maker-core/AGENTS.md
@@ -0,0 +1,13 @@
+# maker-core:Agent 工作入口
+
+本文件适用于 `packages/maker-core/`;[根 AGENTS](../../AGENTS.md) 的授权、system prompt、
+Pi 原生能力、协议兼容与交付规则仍然适用。
+
+- 修改 Agent 编排、prompt 组装、tool/MCP 暴露、translator、model 映射、usage 计量,
+ 或任何进入模型 system 段的提示词前,必须先读
+ [maker-core 与 Agent 行为](../../docs/dev-rules/maker-core-and-agent-behavior.md)。
+- Pi harness 的专用规则见[Pi harness](../../docs/dev-rules/pi-harness.md);
+ 跨 package 依赖与宿主注入边界见[架构不变量](../../docs/dev-rules/architecture-invariants.md)。
+ 这些专题的触发条件和红线保留在根入口,不因调用方位于其他模块而失效。
+- 宿主发送、权限切换与恢复入口,以及相应测试见
+ [仓库地图的行为导航](../../docs/dev-rules/repo-map.md#按用户行为定位);修改核心行为时一并定位调用方。
diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjs
index 6e4af77bee..0adf9575f5 100644
--- a/scripts/__tests__/dev-docs-contract.test.mjs
+++ b/scripts/__tests__/dev-docs-contract.test.mjs
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
@@ -111,14 +112,21 @@ function localMarkdownLinks(relativePath) {
}
/**
- * 需要做内链体检的全部文档:根目录规则文件 + `docs/` 下所有 markdown(递归)。
+ * 需要做内链体检的全部文档:根目录与模块 AGENTS + `docs/` 下所有 markdown(递归)。
*
* 覆盖面刻意做全 —— 悬空内链最容易出现在深层目录里:文档被删除时,引用它的索引
* (如 `docs/legal/README.md`、`docs/README.md`)常常漏改。只体检 CHECKED_DOCS 那几篇
* canonical 文档挡不住这类回归。
*/
function listLinkCheckedDocs() {
- const out = ["AGENTS.md", ...CONTRIBUTING_DOCS];
+ // Include newly added, unstaged module rules without traversing node_modules,
+ // runtime binaries or generated build trees. Git is already required by the runner.
+ const agentDocs = execFileSync("git", [
+ "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--",
+ "AGENTS.md", ":(glob)apps/**/AGENTS.md", ":(glob)packages/**/AGENTS.md",
+ ], { cwd: ROOT, encoding: "utf8" }).split("\0").filter((relativePath) =>
+ relativePath && fs.existsSync(path.join(ROOT, relativePath)));
+ const out = ["AGENTS.md", ...agentDocs, ...CONTRIBUTING_DOCS];
const walk = (relativeDir) => {
for (const entry of fs.readdirSync(path.join(ROOT, relativeDir), { withFileTypes: true })) {
const relativePath = path.join(relativeDir, entry.name);
diff --git a/scripts/__tests__/repo-worktrees.test.mjs b/scripts/__tests__/repo-worktrees.test.mjs
new file mode 100644
index 0000000000..4792fc0a9f
--- /dev/null
+++ b/scripts/__tests__/repo-worktrees.test.mjs
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { classifyWorktree, parseWorktreeStatus } from '../repo-worktrees.mjs';
+
+// Regression: a new worktree starts at a commit already in main. Git ancestry
+// cannot establish that its owning task is finished or that removal is safe.
+// The report must also retain OPEN PR and unreadable-status evidence. Unit tier;
+// classifyWorktree is the same production entry used by the CLI, without I/O.
+const cleanTask = {
+ branch: 'feature/current-task',
+ detached: false,
+ dirty: 0,
+ inBase: true,
+ upstream: 'none',
+ aheadOfUpstream: null,
+ pr: null,
+};
+
+// Entry-point regression: Node resolves import.meta.url, but argv may retain a
+// directory symlink (including macOS /var temp paths). The CLI must actually run.
+test('the CLI works through a linked directory without requiring a repository for help', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-worktree-report-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const link = path.join(root, 'scripts');
+ try {
+ fs.symlinkSync(fileURLToPath(new URL('..', import.meta.url)), link, 'junction');
+ } catch (error) {
+ if (!['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) throw error;
+ t.skip(`directory links unavailable: ${error.code}`);
+ return;
+ }
+ const output = execFileSync(process.execPath, [path.join(link, 'repo-worktrees.mjs'), '--help'], {
+ cwd: root, encoding: 'utf8',
+ });
+ assert.match(output, /clean HEAD in base/);
+ assert.match(output, /不判定任何工作区可删除/);
+});
+
+test('a clean task at the base commit reports ancestry without authorizing cleanup', () => {
+ assert.equal(classifyWorktree(cleanTask), 'clean HEAD in base');
+});
+
+test('an open PR remains active even when its current HEAD is in base', () => {
+ assert.equal(classifyWorktree({ ...cleanTask, pr: { state: 'OPEN' } }), 'active PR');
+});
+
+test('unreadable status is not reported as clean', () => {
+ assert.equal(classifyWorktree({ ...cleanTask, ...parseWorktreeStatus(null) }), 'status unavailable');
+ assert.equal(classifyWorktree({ ...cleanTask, ...parseWorktreeStatus('') }), 'clean HEAD in base');
+});
+
+test('existing dirty and unpushed work remain visible', () => {
+ for (const [patch, expected] of [
+ [{ detached: true, dirty: 1 }, 'detached dirty danger'],
+ [{ dirty: 1 }, 'HEAD merged, worktree dirty'],
+ [{ dirty: 1, inBase: false }, 'dirty WIP'],
+ [{ inBase: false }, 'local unpushed feature'],
+ [{ inBase: false, upstream: 'origin/feature', aheadOfUpstream: 1 }, 'local unpushed feature'],
+ ])
+ assert.equal(classifyWorktree({ ...cleanTask, ...patch }), expected);
+});
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
index 5934481b07..603ac42fc9 100644
--- a/scripts/check-test-hygiene.mjs
+++ b/scripts/check-test-hygiene.mjs
@@ -19,7 +19,7 @@
// 或基线外的文件出现未豁免的命中,都会失败。门禁对照可信 Git 基准拒绝基线上调,
// 手改 JSON 与 `--update` 均不能绕过;只有确认基准提交还没有基线文件时才首次登记。
-import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { createRequire } from 'node:module';
@@ -1454,7 +1454,9 @@ export async function main(args = process.argv.slice(2)) {
return 1;
}
-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+// macOS temp directories and linked CLI entrypoints may spell the same file
+// differently from import.meta.url, which Node resolves to its real path.
+if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().then((code) => { process.exitCode = code; }, (error) => {
console.error(`[test-hygiene] ${error.message}`);
process.exitCode = 2;
diff --git a/scripts/repo-worktrees.mjs b/scripts/repo-worktrees.mjs
index 507a79103a..a50011f07c 100644
--- a/scripts/repo-worktrees.mjs
+++ b/scripts/repo-worktrees.mjs
@@ -1,6 +1,8 @@
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
+import { existsSync, realpathSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
const HELP = `pnpm repo:worktrees — 只读巡检本仓库全部 git worktree,按风险分类输出报告。
@@ -13,26 +15,23 @@ const HELP = `pnpm repo:worktrees — 只读巡检本仓库全部 git worktree,
--help 显示本说明
分类(按风险从高到低排序):
+ status unavailable Git 无法读取工作区状态,不能判断是否干净
detached dirty danger detached HEAD 且有未提交改动,最危险
HEAD merged, worktree dirty 分支已合入基线,但工作区有未提交改动(dirty-tail,人工判断弃留)
dirty WIP 在途工作,有未提交改动
local unpushed feature 本地未推送的功能分支(无 upstream,或领先 upstream 有未 push 提交)
active PR 关联 open PR,勿动
clean branch / PR <state> 干净分支 / PR 已关闭或合并
- detached clean detached HEAD 且干净(临时检出,如 review-pr --detach 产物),确认无用后可移除 worktree
- clean merged removable 已合入且干净,可安全删除(worktree + 本地分支)
+ detached clean detached HEAD 且干净,用途与任务归属尚未核对
+ clean HEAD in base HEAD 已在基线且工作区干净,也可能是刚建好的任务
main clean main 基线现场
说明:本脚本纯只读、不删除任何东西;PR 状态来自 gh CLI(未登录时该列为 "-")。
-清理动作请按报告另行执行。
+报告不查询 Cindy 活跃任务,不判定任何工作区可删除。清理前仍须核对任务归属、
+PR 终态、未推送修改与保留标记,并走现有 cleanup planner。
`;
-if (process.argv.includes('--help') || process.argv.includes('-h')) {
- process.stdout.write(HELP);
- process.exit(0);
-}
-
function git(args, options = {}) {
return execFileSync('git', args, {
cwd: options.cwd,
@@ -93,16 +92,20 @@ function parseWorktrees(text) {
}
function fetchPrRows(root, state) {
- const gh = tryExec('gh', [
- 'pr',
- 'list',
- '--state',
- state,
- '--limit',
- '200',
- '--json',
- 'headRefName,number,state,isDraft,title,url,isCrossRepository',
- ], { cwd: root });
+ const gh = tryExec(
+ 'gh',
+ [
+ 'pr',
+ 'list',
+ '--state',
+ state,
+ '--limit',
+ '200',
+ '--json',
+ 'headRefName,number,state,isDraft,title,url,isCrossRepository',
+ ],
+ { cwd: root },
+ );
if (!gh) return [];
try {
return JSON.parse(gh);
@@ -138,7 +141,12 @@ function loadPrMap(root) {
}
function countStatus(path) {
- const output = tryGit(['-C', path, 'status', '--porcelain=v1']) ?? '';
+ const output = tryGit(['-C', path, 'status', '--porcelain=v1']);
+ return parseWorktreeStatus(output);
+}
+
+export function parseWorktreeStatus(output) {
+ if (output === null) return { dirty: null, untracked: null, tracked: null };
const lines = output.split('\n').filter(Boolean);
return {
dirty: lines.length,
@@ -157,20 +165,23 @@ function aheadBehind(path, base) {
};
}
-function classify(row) {
+export function classifyWorktree(row) {
+ if (row.dirty === null) return 'status unavailable';
if (row.detached && row.dirty > 0) return 'detached dirty danger';
if (row.dirty > 0 && row.inBase) return 'HEAD merged, worktree dirty';
if (row.dirty > 0) return 'dirty WIP';
// detached + 干净 = 临时检出(review-pr --detach 等),没有分支可推送/删除,
- // 不能落进 local unpushed feature / clean merged removable 的分支语义里。
+ // 不据此判断临时检出或个人构建是否仍有使用者。
if (row.detached) return 'detached clean';
// main 本地领先 upstream(有未 push 的 commit)时不是干净基线,同样按未推送
// 的活处理,不能藏进最低风险的 main clean。
if (row.branch === 'main') {
return (row.aheadOfUpstream ?? 0) > 0 ? 'local unpushed feature' : 'main clean';
}
- if (row.inBase) return 'clean merged removable';
- if (row.pr) return row.pr.state === 'OPEN' ? 'active PR' : `PR ${row.pr.state.toLowerCase()}`;
+ if (row.pr?.state === 'OPEN') return 'active PR';
+ // 新任务的初始 HEAD 同样在基线里,祖先关系不能证明 owning session 已结束。
+ if (row.inBase) return 'clean HEAD in base';
+ if (row.pr) return `PR ${row.pr.state.toLowerCase()}`;
if (row.upstream === 'none') return 'local unpushed feature';
// 有 upstream 但本地领先(未 push 的提交)同样是未推送的活,不能归入 clean branch。
if ((row.aheadOfUpstream ?? 0) > 0) return 'local unpushed feature';
@@ -203,7 +214,7 @@ function printTable(rows) {
for (const row of rows) {
const values = {
class: row.classification,
- dirty: `${row.dirty}/${row.untracked}`,
+ dirty: `${row.dirty ?? '?'}/${row.untracked ?? '?'}`,
branch: row.branch,
base: row.inBase ? 'in-main' : 'not-main',
'ahead/behind': `${row.ahead ?? '?'}/${row.behind ?? '?'}`,
@@ -214,80 +225,88 @@ function printTable(rows) {
}
}
-const root = git(['rev-parse', '--show-toplevel']);
-const base = process.argv.includes('--base')
- ? process.argv[process.argv.indexOf('--base') + 1]
- : 'origin/main';
-const asJson = process.argv.includes('--json');
+export function main() {
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
+ process.stdout.write(HELP);
+ return;
+ }
+ const root = git(['rev-parse', '--show-toplevel']);
+ const base = process.argv.includes('--base') ? process.argv[process.argv.indexOf('--base') + 1] : 'origin/main';
+ const asJson = process.argv.includes('--json');
-// base 解析不了时 merge-base / rev-list 会对所有 worktree 静默失败,整份报告的
-// in-main / ahead/behind 全部失真却无任何提示——必须在这里硬失败。
-// 覆盖两种常见情形:--base 漏传值(undefined / 吞掉下一个 flag)、基线 ref 本地
-// 不存在(origin/main 未 fetch / 拼错)。
-if (!base || base.startsWith('-')) {
- console.error('error: --base 缺少值(用法: pnpm repo:worktrees --base <ref>)');
- process.exit(1);
-}
-if (!commandOk('git', ['rev-parse', '--verify', '--quiet', `${base}^{commit}`], { cwd: root })) {
- console.error(
- `error: 基线 "${base}" 无法解析为 commit。origin/* 基线请先 git fetch origin;自定义 --base 请检查拼写。`,
- );
- process.exit(1);
-}
+ // base 解析不了时 merge-base / rev-list 会对所有 worktree 静默失败,整份报告的
+ // in-main / ahead/behind 全部失真却无任何提示——必须在这里硬失败。
+ // 覆盖两种常见情形:--base 漏传值(undefined / 吞掉下一个 flag)、基线 ref 本地
+ // 不存在(origin/main 未 fetch / 拼错)。
+ if (!base || base.startsWith('-')) {
+ console.error('error: --base 缺少值(用法: pnpm repo:worktrees --base <ref>)');
+ process.exit(1);
+ }
+ if (!commandOk('git', ['rev-parse', '--verify', '--quiet', `${base}^{commit}`], { cwd: root })) {
+ console.error(
+ `error: 基线 "${base}" 无法解析为 commit。origin/* 基线请先 git fetch origin;自定义 --base 请检查拼写。`,
+ );
+ process.exit(1);
+ }
-const prMap = loadPrMap(root);
-const worktrees = parseWorktrees(git(['worktree', 'list', '--porcelain']));
-const rows = worktrees.map((worktree) => {
- const branch = tryGit(['-C', worktree.path, 'symbolic-ref', '--short', '-q', 'HEAD']) ?? 'DETACHED';
- const upstream = tryGit(['-C', worktree.path, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']) ?? 'none';
- // 领先自己 upstream 的 commit 数:有 upstream 但本地还有未 push 的提交时,
- // 该分支不能被当成低风险 clean branch(删了会丢未推送的活)。
- const aheadOfUpstreamRaw =
- upstream === 'none' ? null : tryGit(['-C', worktree.path, 'rev-list', '--count', '@{u}..HEAD']);
- const aheadOfUpstream =
- aheadOfUpstreamRaw === null ? null : Number.parseInt(aheadOfUpstreamRaw, 10) || 0;
- const status = countStatus(worktree.path);
- const inBase = commandOk('git', ['-C', worktree.path, 'merge-base', '--is-ancestor', 'HEAD', base]);
- const counts = aheadBehind(worktree.path, base);
- const subject = tryGit(['-C', worktree.path, 'log', '-1', '--format=%s']) ?? '';
- const row = {
- path: worktree.path,
- branch,
- head: (worktree.head ?? '').slice(0, 12),
- detached: branch === 'DETACHED',
- upstream,
- aheadOfUpstream,
- inBase,
- ahead: counts.ahead,
- behind: counts.behind,
- dirty: status.dirty,
- tracked: status.tracked,
- untracked: status.untracked,
- subject,
- pr: prMap.get(branch) ?? null,
- };
- return { ...row, classification: classify(row) };
-});
+ const prMap = loadPrMap(root);
+ const worktrees = parseWorktrees(git(['worktree', 'list', '--porcelain']));
+ const rows = worktrees.map((worktree) => {
+ const branch = tryGit(['-C', worktree.path, 'symbolic-ref', '--short', '-q', 'HEAD']) ?? 'DETACHED';
+ const upstream =
+ tryGit(['-C', worktree.path, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']) ?? 'none';
+ // 领先自己 upstream 的 commit 数:有 upstream 但本地还有未 push 的提交时,
+ // 该分支不能被当成低风险 clean branch(删了会丢未推送的活)。
+ const aheadOfUpstreamRaw =
+ upstream === 'none' ? null : tryGit(['-C', worktree.path, 'rev-list', '--count', '@{u}..HEAD']);
+ const aheadOfUpstream = aheadOfUpstreamRaw === null ? null : Number.parseInt(aheadOfUpstreamRaw, 10) || 0;
+ const status = countStatus(worktree.path);
+ const inBase = commandOk('git', ['-C', worktree.path, 'merge-base', '--is-ancestor', 'HEAD', base]);
+ const counts = aheadBehind(worktree.path, base);
+ const subject = tryGit(['-C', worktree.path, 'log', '-1', '--format=%s']) ?? '';
+ const row = {
+ path: worktree.path,
+ branch,
+ head: (worktree.head ?? '').slice(0, 12),
+ detached: branch === 'DETACHED',
+ upstream,
+ aheadOfUpstream,
+ inBase,
+ ahead: counts.ahead,
+ behind: counts.behind,
+ dirty: status.dirty,
+ tracked: status.tracked,
+ untracked: status.untracked,
+ subject,
+ pr: prMap.get(branch) ?? null,
+ };
+ return { ...row, classification: classifyWorktree(row) };
+ });
-rows.sort((a, b) => {
- const rank = {
- 'detached dirty danger': 0,
- 'HEAD merged, worktree dirty': 1,
- 'dirty WIP': 2,
- 'local unpushed feature': 3,
- 'active PR': 4,
- 'clean branch': 5,
- 'detached clean': 6,
- 'clean merged removable': 7,
- 'main clean': 8,
- };
- return (rank[a.classification] ?? 5) - (rank[b.classification] ?? 5) || a.path.localeCompare(b.path);
-});
+ rows.sort((a, b) => {
+ const rank = {
+ 'status unavailable': -1,
+ 'detached dirty danger': 0,
+ 'HEAD merged, worktree dirty': 1,
+ 'dirty WIP': 2,
+ 'local unpushed feature': 3,
+ 'active PR': 4,
+ 'clean branch': 5,
+ 'detached clean': 6,
+ 'clean HEAD in base': 7,
+ 'main clean': 8,
+ };
+ return (rank[a.classification] ?? 5) - (rank[b.classification] ?? 5) || a.path.localeCompare(b.path);
+ });
-if (asJson) {
- console.log(JSON.stringify({ base, rows }, null, 2));
-} else {
- console.log(`Base: ${base}`);
- console.log('dirty is total/untracked');
- printTable(rows);
+ if (asJson) {
+ console.log(JSON.stringify({ base, cleanupVerified: false, rows }, null, 2));
+ } else {
+ console.log(`Base: ${base}`);
+ console.log('dirty is total/untracked');
+ console.log('Task ownership is not checked; no classification authorizes removal.');
+ printTable(rows);
+ }
}
+
+if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) main();