Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test(mobile): align guards with extracted session modules
Dash55f748f83853
diff --git a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.tsindex 721b97b17f..5a9cc3e783 100644--- a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts+++ b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts@@ -5,11 +5,11 @@ 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[] | undefined, options: { preSend(): void }) => {- options.preSend(); return { id: 'session', source: 'cc' };+ const invoke = vi.fn(async (_device: string, _channel: string, _args: unknown[] | undefined, options: { preSend(): void }): Promise<{ id: string; source: string; workingDir?: string }> => {+ options.preSend(); return { id: 'session', source: 'cc', workingDir: '/repo' };});const latest = { current: { link: { status: 'online', getPresenceAvailability: () => true, invoke } } };- const owner = { current: true, records: [record] };+ const owner = { current: true, records: [record], creationHeld: false };const hasCreationTask = vi.fn(() => false);const callbacks = createOutboxSessionAccess({getSessions: () => sessions,@@ -18,7 +18,7 @@ function harness(sessions: Array<{ id: string; source?: string; deviceLinkDeviceisCurrent: () => owner.current,isForeground: () => true,canConnect: () => latest.current.link.status === 'online' && latest.current.link.getPresenceAvailability() !== false,- isCreationHeld: () => false,+ isCreationHeld: () => owner.creationHeld,hasCreationTask,needsReconciliation: () => true,invoke: (deviceId, channel, args, options) => latest.current.link.invoke(deviceId, channel, args, options),@@ -28,6 +28,29 @@ function harness(sessions: Array<{ id: string; source?: string; deviceLinkDevice}describe('Cindy Make outbox bridge guards', () => {+ // mobile-development: follow-ups wait for creation ownership, while policy and+ // preparation reuse the same authoritative row. Replaces old bridge literals.+ it('waits for both draft handoff and task creation before allowing delivery', () => {+ const { record, callbacks, owner, hasCreationTask } = harness([]);+ owner.creationHeld = true;+ expect(callbacks.canRun(record)).toBe(false);+ expect(hasCreationTask).not.toHaveBeenCalled();+ owner.creationHeld = false;+ hasCreationTask.mockReturnValue(true);+ expect(callbacks.canRun(record)).toBe(false);+ hasCreationTask.mockReturnValue(false);+ expect(callbacks.canRun(record)).toBe(true);+ });++ it('shares the authoritative task row between preparation and delivery policy', async () => {+ const { record, callbacks, invoke } = harness([]);+ const row = callbacks.readSessionOnce(record);+ await expect(callbacks.sessionPolicy(record)).resolves.toBe('deliver');+ await expect(row).resolves.toMatchObject({ id: 'session', workingDir: '/repo' });+ expect(callbacks.readSessionOnce(record)).toBe(row);+ expect(invoke).toHaveBeenCalledOnce();+ });+// 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 () => {diff --git a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts b/apps/mobile/src/__tests__/mobileGoalCommands.test.tsindex 7e49a3d18d..cdf1bfb9d3 100644--- a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts+++ b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts@@ -7,6 +7,9 @@ import { executeMobileGoalCommand, parseMobileDesktopCommand } from '@/session/dimport { humanizeRemoteError } from '@/device-link/remoteStatus';import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';import { composerDocumentProjectedText, emptyComposerDocument, normalizeComposerDocument, reconcileComposerProjectedText, serializeComposerDocument, textComposerDocument } from '@/session/composerDocument';+import { captureNewSessionOwner } from '@/session/newSessionForm';+import { reconcileNewSessionSubmitDraft } from '@/session/newSessionRuntimeReconciliation';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, setMobileAuthOwner } from '@/auth/authOwnerGeneration';// Execute the actual page callbacks, excluding unrelated native/network UI.function callback(path: string, name: string) {@@ -40,6 +43,7 @@ if (!readRouteParamSource) throw new Error('Missing SessionScreen.readRouteParamconst compiledExisting = ts.transpileModule(`${readRouteParamSource}\n${sendSource}\nreturn send;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;function newHarness(text = '/goal target') {+ setMobileAuthOwner('test-user');const noop = vi.fn();const draft = { agentKind: 'pi', model: 'test-model', providerId: 'test-provider', workspaceKind: 'dialogue', workingDir: '', firstMessage: text, agentDeviceId: 'agent-device' };const bindings = {@@ -51,13 +55,13 @@ function newHarness(text = '/goal target') {leaveForeignOutboxRecovery: () => false, goalBusy: false, runtimePendingRef: { current: false },selectedDeviceId: 'host', selectedDeviceName: 'Host', selectedDeviceRef: { current: 'host' },draft, remoteAgentPick: {}, deviceProvidersRef: { current: { ready: false } },- captureWorktreeCreateIntent: () => ({ applicable: false, enabled: false }), isWorktreeCreateIntentCurrent: () => true,+ prepareWorktreeCreateIntent: () => ({ applicable: false, enabled: false }), isWorktreeCreateIntentCurrent: () => true,setCreating: noop, setGoalBusy: noop, auth: { user: { id: 'test-user' } },- getMobileAuthOwner: () => ({ accountId: 'test-user' }), isMobileAuthOwnerCurrent: () => true,+ getMobileAuthOwner, isMobileAuthOwnerCurrent, captureNewSessionOwner,agentAuthVerdict: 'ready', applyRemoteAgentPick: (value: unknown) => value,createNewSessionId: () => 'new-goal-task', saveNewSessionPreferences: noop,- getDeviceProvidersGen: () => 1, resolveRecentModelAndProvider: (_rows: unknown, selected: unknown) => selected,- assertSubmitModelResolved: noop, withTransientRemoteRetry: (fn: () => Promise<unknown>) => fn(), openLink: noop, subscribe: vi.fn(async () => {}),+ getDeviceProvidersGen: () => 1, reconcileNewSessionSubmitDraft, targetAgentHasFast: () => false,+ withTransientRemoteRetry: (fn: () => Promise<unknown>) => fn(), openLink: noop, subscribe: vi.fn(async () => {}),buildRemoteCreateSessionOptions: (value: unknown) => value, normalizeCreateSessionResult: (value: unknown) => value,maker: { createSession: vi.fn(async () => ({ sessionId: 'new-goal-task' })),goal: { set: vi.fn(async () => {}) }, getSession: vi.fn(async () => ({ id: 'new-goal-task', title: 'Goal task' })) },diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsxindex 3750dadb8d..5b406163cf 100644--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx@@ -16,6 +16,7 @@ import { createInitialNewSessionDraft, patchNewSessionDraft, restoreNewSessionDrimport { useNewSessionStashedDraft, useNewSessionWorkspacePreferences, useNewSessionWorkspaceActions, useNewSessionInitialWorkspace } from '@/session/useNewSessionWorkspace';import { readNewSessionPreferences, saveNewSessionPreferences } from '@/session/newSessionPreferenceStore';import type { RemoteSerializedAttachment, RemoteSession } from '@/session/types';+import type { OrcaWorkerFormValue } from '@/session/orcaTeam';vi.mock('@/session/newSessionPreferenceStore', () => ({readNewSessionPreferences: vi.fn(),@@ -40,7 +41,7 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });let root: Root | undefined;afterEach(() => { act(() => root?.unmount()); root = undefined; });-function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NewSessionWorkspaceKind; suggestion?: string; routeDraft?: string | string[]; deviceExplicit?: boolean } = {}) {+function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NewSessionWorkspaceKind; collabDraft?: OrcaWorkerFormValue; suggestion?: string; routeDraft?: string | string[]; deviceExplicit?: boolean } = {}) {let resolveRead!: (value: NewSessionStoredPreferences) => void;const pendingRead = new Promise<NewSessionStoredPreferences>((resolve) => { resolveRead = resolve; });const deviceOptions = [{ deviceId: 'a', name: 'A' }, { deviceId: 'b', name: 'B' }];@@ -59,8 +60,9 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Nedraft: { ...DEFAULT_NEW_SESSION_DRAFT, workspaceKind: options.restoredKind,workingDir: options.restoredKind === 'project' ? '/restored/project' : '',firstMessage: 'restored draft' },- attachments: [], deviceId: 'a', deviceName: 'A', notice: null, collabDraft: null,+ attachments: [], deviceId: 'a', deviceName: 'A', notice: null, collabDraft: options.collabDraft ?? null,} : null),+ onRestoreCollab: vi.fn(),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(),@@ -109,7 +111,7 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NeworkingDirPreferenceOverridesRef, initialWorkspaceKeyRef, appliedDefaultDeviceKeyRef,userTouchedDeviceRef, userTouchedWorkspaceRef, draft, setDraft, preferredDefaultDevice };useNewSessionStashedDraft({ ...common, sessionId: bindings.params.editSessionId, deviceId: 'a',- restoreCreationDraft, onRestoreCollab: () => {} });+ restoreCreationDraft });useNewSessionWorkspacePreferences(common);const patchDraft = useCallback((patch: Partial<NewSessionDraft>) => patchNewSessionDraft({...bindings, firstMessageRef, setDraft,@@ -201,13 +203,21 @@ describe('new session workspace page effects', () => {});it.each(['project', 'dialogue'] as const)('preserves a restored %s draft over a late default', async (kind) => {- const page = mountWorkspace({ restoredKind: kind, suggestion: 'findFile' });+ // Creation recovery must restore the associated Worker plan along with the+ // Lead's input; the former page-literal guard could miss a disconnected hook.+ const collabDraft: OrcaWorkerFormValue = {+ role: 'Worker', agent: 'pi', model: null, permissionMode: 'auto', initialTask: 'review changes',+ };+ const page = mountWorkspace({ restoredKind: kind, suggestion: 'findFile', collabDraft });expect(page.bindings.drainStashedNewSessionDraft).toHaveBeenCalledExactlyOnceWith('failed-task', 'a');await page.resolvePreferences(kind === 'project' ? 'dialogue' : 'project', 'b');expect(page.current.draft).toMatchObject({ workspaceKind: kind,workingDir: kind === 'project' ? '/restored/project' : '' });expect(page.current.selectedDeviceId).toBe('a');expect(page.current.firstMessageSelection).toEqual({ start: 'restored draft'.length, end: 'restored draft'.length });+ expect(page.bindings.onRestoreCollab).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ deviceId: 'a', collabDraft, draft: expect.objectContaining({ firstMessage: 'restored draft' }),+ }));});it.each(['project', 'dialogue'] as const)('preserves a manual %s choice made during the read', async (kind) => {diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex a1c3b58b54..a4f47afe63 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -129,10 +129,12 @@ describe('mobile optimistic composer while session is not ready', () => {it('lets the app owner obtain authoritative parameters before dispatch, independently of the page', () => {const bridge = readSource('src/session/MobileOutboxBridge.tsx');- expect(bridge).toContain('getNewSessionCreationTask(r.item.sessionId) === null');- expect(bridge).toContain('!isDurableOutboxCreationHeld(r.item.sessionId)');- // Preparation reads the Host's row; the policy check of the same message may share that read.- expect(bridge).toContain('const read = maker(r).getSession(r.item.sessionId)');+ // Ownership/creation guards and shared reads run through the production+ // adapter in cindyMakeOutboxBridge.test.ts; retain the app-owner wiring here.+ expect(bridge).toContain('= createOutboxSessionAccess({');+ expect(bridge).toContain('hasCreationTask: (sessionId) => getNewSessionCreationTask(sessionId) !== null');+ expect(bridge).toContain('isCreationHeld: isDurableOutboxCreationHeld');+ expect(bridge).toContain('readSession: (record) => maker(record).getSession(record.item.sessionId)');expect(bridge).toContain('const session = await readSessionOnce(r)');expect(bridge).toContain('if (!session?.workingDir)');expect(bridge).toContain('}, [link.status, link.connectionEpoch])');@@ -236,7 +238,9 @@ describe('mobile optimistic composer while session is not ready', () => {const bridge = readSource('src/session/MobileOutboxBridge.tsx');const delivery = readSource('src/session/durableOutboxDelivery.ts');expect(source).not.toContain('const dispatchOutboxItem =');- expect(bridge).toContain('preSend: guardRecord');+ // The transport must use the record-scoped adapter, whose delayed pre-send+ // invalidation is exercised by cindyMakeOutboxBridge.test.ts.+ expect(bridge).toContain('invoke: invokeOwned(r),');expect(delivery).toMatch(/await update\(\{\s*state: ["']sending["'],\s*enqueueStarted: true,\s*error: undefined\s*\}\)/);expect(delivery).toContain('record.retrySafe && projection.inputDeliveryVersion === 1');expect(delivery).not.toContain('createOutboxClientId');diff --git a/apps/mobile/src/__tests__/orcaCollabScreenWiring.test.ts b/apps/mobile/src/__tests__/orcaCollabScreenWiring.test.tsindex 41dfa18438..e45e8c441a 100644--- a/apps/mobile/src/__tests__/orcaCollabScreenWiring.test.ts+++ b/apps/mobile/src/__tests__/orcaCollabScreenWiring.test.ts@@ -83,6 +83,10 @@ describe('mobile Orca collaboration wiring', () => {expect(source).toContain('prefsScope: outboxOwner.accountKey || null,');// create-failed「返回编辑」带回协同草稿;目标比对防止恢复时被「换目标即清」误清。expect(source).toContain('if (collabDraftTargetRef.current !== collabTargetKey) setCollabDraft(null);');- expect(source).toContain('if (stashed.collabDraft && stashed.deviceId) {');+ // The stashed-draft hook owns the restoration condition after extraction.+ // Keep the cross-entry handoff guarded; hook behavior is mounted in+ // newSessionWorkspaceEffects.test.tsx.+ expect(source).toContain('useNewSessionStashedDraft({');+ expect(source).toContain('onRestoreCollab:');});});diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.tsindex 691a33455a..df6bbb7b2b 100644--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts@@ -28,8 +28,9 @@ describe('new task remote Agent wiring', () => {expect(source.split('const runGuard = () => effectiveDraft.agentDeviceId ? Promise.resolve({')).toHaveLength(3);expect(source).toContain('confirmUnauthenticated: effectiveDraft.agentDeviceId');expect(source).toContain("agentAuthVerdict === 'unauthenticated' || remoteAgentPick");- // 恢复草稿时把 Agent 所在电脑拆回远程选择。- expect(source).toContain('const { agentDeviceId, ...recovered } = saved;');+ // 恢复的远程位置拆分行为由 newSessionDraftRecovery.test.ts 直接调用生产+ // restoreNewSessionDraft 覆盖;这里保留页面接入,防止恢复时漏掉被控电脑身份。+ expect(source).toMatch(/restoreNewSessionDraft\(\s*\{\s*setRemoteAgentChoice,/);});});diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.tsindex 6c725ed7d7..1eef425870 100644--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts@@ -91,8 +91,12 @@ describe('任务消息内存治理页面接线', () => {expect(screen).toContain('enabled: appStateActive && remoteHistoryAvailable && !isScheduleDetail,');expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, pageHasMessageWork)');const bridge = source('src/session/MobileOutboxBridge.tsx');- expect(bridge).toMatch(/remoteSessionStore\.acquireSessionMessageWork\(\s*record\.item\.sessionId,\s*true,?\s*\)/);- expect(bridge).toContain('for (const lease of leases.values()) lease.release()');+ // Lease acquisition/release behavior is exercised through the production+ // adapter in newSessionCreation.test.ts. This guard protects effect cleanup.+ expect(bridge).toContain('const messageLeases = createOutboxMessageLeases({');+ expect(bridge).toContain('store: remoteSessionStore,');+ expect(bridge).toContain('messageLeases.refresh();');+ expect(bridge).toContain('messageLeases.dispose();');expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, true)');expect(screen.match(/messageWorkLease\.release\(\);/g)).toHaveLength(1);for (const signal of [