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。

143 KB
Raw Blame
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';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
import type { MobileModelOption } from '@/session/agentCapabilities';
import {
  DEFAULT_NEW_SESSION_DRAFT,
  NEW_SESSION_AGENT_OPTIONS,
  availableNewSessionAgentOptions,
  canResolveStoredAgentRuntime,
  assertSubmitModelResolved,
  isNewSessionRuntimePending,
  isStoredAgentRestorePending,
  nextStoredAgentRestoreStep,
  type StoredAgentRestoreState,
  type NewSessionRuntime,
  buildNewSessionCreatePreview,
  buildRecentWorkspaceOptions,
  applyRemoteAgentPick,
  buildRemoteCreateSessionOptions,
  filterRemoteDirectoryEntries,
  isCurrentRemoteBrowseRequest,
  normalizeRemoteDirectoryDrives,
  shouldRetryRemoteBrowseDrives,
  defaultPermissionModeForNewSessionAgent,
  normalizeCreateSessionResult,
  parseNewSessionDeviceOptions,
  parseExtraDirsInput,
  pickAgentDefaultRuntime,
  pickInitialNewSessionWorkspace,
  hostDraftRuntimeFromDefaults,
  isHostDraftDefaultsReady,
  pickNewSessionDefaultDevice,
  resolveNewSessionAutoDefault,
  resolveRecentModelAndProvider,
  resolveSubmitGuardCatalog,
  resolveStartedDowngradeOrCommit,
  sessionFromCreateResult,
  compensatePrecreatedWorktree,
  reconcileEffortAfterFallback,
  serializeNewSessionDeviceOptions,
  summarizeNewSessionDraft,
  validateModelProviderId,
  validateNewSessionDraft,
  withAgentDefaults,
} from '@/session/newSession';
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)。
beforeAll(async () => {
  await i18n.changeLanguage('zh-CN');
});

function modelRow(
  id: string,
  efforts: readonly string[] = [],
  defaultEffort: string | null = null,
  newSessionDefault?: readonly ('claude-code' | 'codex' | 'pi')[],
): ProviderModelRow {
  return {
    provider: { id: `prov-${id}`, name: id } as ProviderModelRow['provider'],
    model: {
      id,
      displayName: id,
      efforts: efforts as ProviderModelRow['model']['efforts'],
      defaultEffort: defaultEffort as ProviderModelRow['model']['defaultEffort'],
      contextWindow: 0,
      ...(newSessionDefault ? { newSessionDefault: [...newSessionDefault] } : {}),
    },
  };
}

function remoteSession(id: string, patch: Partial<RemoteSession> = {}): RemoteSession {
  return {
    id,
    userId: 'u1',
    title: id,
    workingDir: '/repo/app',
    workspaceKind: 'project',
    model: 'claude-sonnet-4-6',
    effort: 'medium',
    permissionMode: 'acceptEdits',
    fastMode: false,
    status: 'active',
    agentKind: 'cc',
    userSendAt: null,
    createdAt: '2026-01-01T00:00:00.000Z',
    updatedAt: '2026-01-01T00:00:00.000Z',
    ...patch,
  };
}

// 异步时序测试工具(文件级,供多个 describe 共用)。
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
const deferred = <T,>() => {
  let resolve!: (v: T) => void;
  let reject!: (e: unknown) => void;
  const promise = new Promise<T>((r, j) => { resolve = r; reject = j; });
  return { promise, resolve, reject };
};

function hostRuntime(
  agentKind: NewSessionRuntime['agentKind'],
  model: string,
  patch: Partial<Omit<NewSessionRuntime, 'agentKind' | 'model'>> = {},
): NewSessionRuntime {
  return { agentKind, model, effort: 'medium', providerId: null, ...patch };
}

describe('hostDraftRuntimeFromDefaults', () => {
  it('reads the host new-task default (model + effort + source) for the agent', () => {
    expect(hostDraftRuntimeFromDefaults(
      { model: 'claude-opus-5-5', effort: 'high', providerId: 'anthropic', modelChosenByUser: true, worktreeEnabled: false },
      'claude-code',
    )).toEqual({ agentKind: 'claude-code', model: 'claude-opus-5-5', effort: 'high', providerId: 'anthropic' });
    // providerId 缺省 / 空串 = 跟随被控端默认来源;旧端不回 modelChosenByUser 时保守采用其 model。
    expect(hostDraftRuntimeFromDefaults({ model: 'gpt-6-astra', providerId: '' }, 'codex'))
      .toEqual({ agentKind: 'codex', model: 'gpt-6-astra', effort: '', providerId: null });
  });

  it('returns null for old hosts, malformed payloads and empty drafts', () => {
    expect(hostDraftRuntimeFromDefaults({}, 'claude-code')).toBeNull();
    expect(hostDraftRuntimeFromDefaults({ worktreeEnabled: true }, 'claude-code')).toBeNull();
    expect(hostDraftRuntimeFromDefaults(null, 'claude-code')).toBeNull();
    expect(hostDraftRuntimeFromDefaults('claude-opus-5-5', 'claude-code')).toBeNull();
    expect(hostDraftRuntimeFromDefaults({ model: '  ' }, 'claude-code')).toBeNull();
  });

  it('treats a snapshot without worktreeEnabled as not ready yet (host renderer cache not pushed)', () => {
    expect(isHostDraftDefaultsReady({})).toBe(false);
    expect(isHostDraftDefaultsReady({ providerModelMemory: {} })).toBe(false);
    expect(isHostDraftDefaultsReady(null)).toBe(false);
    expect(isHostDraftDefaultsReady({ worktreeEnabled: false })).toBe(true);
    expect(isHostDraftDefaultsReady({ worktreeEnabled: true, model: 'm' })).toBe(true);
  });

  it('leaves a never-chosen host seed to the catalog regional default, like the desktop controller', () => {
    expect(hostDraftRuntimeFromDefaults({ model: 'seed', modelChosenByUser: false, providerId: null }, 'pi')).toBeNull();
    // 选过来源即视为明确选择。
    expect(hostDraftRuntimeFromDefaults({ model: 'seed', modelChosenByUser: false, providerId: 'xd' }, 'pi'))
      .toEqual({ agentKind: 'pi', model: 'seed', effort: '', providerId: 'xd' });
  });
});

describe('reconcileEffortAfterFallback', () => {
  it('keeps the base effort when the fallback model supports it', () => {
    const rows = [modelRow('claude-sonnet-4-6', ['low', 'medium', 'high'], 'medium')];
    expect(reconcileEffortAfterFallback(rows, { model: 'claude-sonnet-4-6', providerId: 'prov-claude-sonnet-4-6' }, 'high')).toBe('high');
  });

  it('drops to the fallback model default when the base effort is unsupported (codex P2)', () => {
    const rows = [modelRow('claude-haiku', ['low'], 'low')];
    expect(reconcileEffortAfterFallback(rows, { model: 'claude-haiku', providerId: 'prov-claude-haiku' }, 'xhigh')).toBe('low');
  });

  it('omits effort when no catalog row matches (built-in default fallback, Codex P2: 不沿用旧模型档位)', () => {
    expect(reconcileEffortAfterFallback([], { model: 'claude-sonnet-4-6', providerId: null }, 'high')).toBe('');
  });
});

describe('validateModelProviderId', () => {
  const rows = [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')];

  it('null / undefined providerId → null', () => {
    expect(validateModelProviderId(rows, null, 'deepseek-v4-flash', true)).toBeNull();
    expect(validateModelProviderId(rows, undefined, 'deepseek-v4-flash', true)).toBeNull();
  });

  it('catalog not ready → trust the binding as-is (terminal truth is the controlled end)', () => {
    expect(validateModelProviderId([], 'deepseek', 'deepseek-v4-flash', false)).toBe('deepseek');
    expect(validateModelProviderId(rows, 'prov-anything', 'm', false)).toBe('prov-anything');
  });

  it('catalog ready + matching (provider, model) row → keep', () => {
    expect(validateModelProviderId(rows, 'prov-deepseek-v4-flash', 'deepseek-v4-flash', true)).toBe('prov-deepseek-v4-flash');
  });

  it('catalog ready + no matching row → clear to default route (incl. loaded-but-empty)', () => {
    expect(validateModelProviderId(rows, 'prov-gone', 'deepseek-v4-flash', true)).toBeNull();
    expect(validateModelProviderId([], 'deepseek', 'deepseek-v4-flash', true)).toBeNull();
    // provider 仍在但不再提供该模型 → 同样清空(不匹配 modelId)
    expect(validateModelProviderId(rows, 'prov-deepseek-v4-flash', 'other-model', true)).toBeNull();
  });
});

describe('resolveSubmitGuardCatalog —— 提交终检目录取信(代际安全,独立 review P1-1)', () => {
  const rowsOf = (id: string) => [modelRow(id, ['low'], 'low')];
  type TestPayload = { id: string; providers: never[] };
  const payload = (id: string): TestPayload => ({ id, providers: [] });
  const baseArgs = {
    gen: () => 1,
    cached: () => undefined as TestPayload | undefined,
    fetch: () => Promise.resolve(payload('fetched')),
    buildRows: (pl: DeviceProvidersPayload) => rowsOf((pl as TestPayload).id),
  };

  it('ordinary creation hands off without awaiting a hung catalog refresh', async () => {
    const fetch = vi.fn(() => new Promise<TestPayload>(() => {}));
    const result = await resolveSubmitGuardCatalog({ ...baseArgs, fetch, cached: () => payload('cached'), deferRefreshToCreation: true });
    expect(result).toEqual({ rows: [], providers: [], catalogKnown: false, genAt: 1 });
    const selected = { model: 'newly-connected-model', providerId: 'newly-connected-provider' };
    expect(resolveRecentModelAndProvider(result.rows, selected, 'codex', result.catalogKnown, result.providers)).toEqual(selected);
    expect(fetch).not.toHaveBeenCalled();
  });

  it('defers an evicted catalog to the post-link check without trusting stale rows', async () => {
    const fetch = vi.fn(baseArgs.fetch);
    const result = await resolveSubmitGuardCatalog({ ...baseArgs, fetch, deferRefreshToCreation: true });
    expect(result).toEqual({ rows: [], providers: [], catalogKnown: false, genAt: 1 });
    expect(fetch).not.toHaveBeenCalled();
  });

  it('缓存命中 → join fetch revalidate,成功用新目录(工作站已换 provider,codex review P1)', async () => {
    const fetchSpy = vi.fn(baseArgs.fetch);
    const res = await resolveSubmitGuardCatalog({
      ...baseArgs,
      cached: () => payload('cached'),
      fetch: fetchSpy,
    });
    // 缓存命中不再直接采信:与新鲜响应 revalidate(缓存层 inflight 去重),成功用新目录
    expect(fetchSpy).toHaveBeenCalledTimes(1);
    expect(res).toMatchObject({ rows: rowsOf('fetched'), catalogKnown: true });
  });

  it('缓存命中 + fetch 失败 → 回退缓存命中(历史知识优于未知,保持 fail-open)', async () => {
    const res = await resolveSubmitGuardCatalog({
      ...baseArgs,
      cached: () => payload('cached'),
      fetch: () => Promise.reject(new Error('revalidate down')),
    });
    expect(res).toMatchObject({ rows: rowsOf('cached'), catalogKnown: true });
  });

  it('冷启动(gen=0)+ 无缓存 → join 首轮拉取(不重复发请求),成功按新目录校验(Codex P2)', async () => {
    const fetchSpy = vi.fn(baseArgs.fetch);
    const res = await resolveSubmitGuardCatalog({ ...baseArgs, gen: () => 0, fetch: fetchSpy });
    expect(fetchSpy).toHaveBeenCalledTimes(1);
    expect(res).toMatchObject({ rows: rowsOf('fetched'), catalogKnown: true });
  });

  it('冷启动(gen=0)+ 首轮拉取失败 → 未知 → 信任(fail-open 语义保持)', async () => {
    const res = await resolveSubmitGuardCatalog({
      ...baseArgs,
      gen: () => 0,
      fetch: () => Promise.reject(new Error('first load down')),
    });
    expect(res).toMatchObject({ rows: [], catalogKnown: false });
  });

  it('曾驱逐(gen>0)+ 无缓存 → join 在途重拉,代际稳定时采信新 payload', async () => {
    const res = await resolveSubmitGuardCatalog(baseArgs);
    expect(res).toMatchObject({ rows: rowsOf('fetched'), catalogKnown: true });
  });

  it('await 期间二次驱逐(gen g1→g2)→ 弃用 g1 旧 promise 返回值,join 新代第二次 fetch', async () => {
    // 独立 review P1-1 窗口:缓存层只拒绝旧响应回写、仍 resolve 旧 payload——
    // 调用方不得消费它;必须核对代际后 join 新代。
    let gen = 1;
    const d1 = deferred<TestPayload>();
    const fetchSpy = vi.fn(() => {
      const g = gen;
      return g === 1 ? d1.promise : Promise.resolve(payload('g2'));
    });
    const pending = resolveSubmitGuardCatalog({ ...baseArgs, gen: () => gen, fetch: fetchSpy });
    await flush();
    expect(fetchSpy).toHaveBeenCalledTimes(1);
    gen = 2; // 二次驱逐
    d1.resolve(payload('g1')); // g1 最后才 resolve → 返回值必须被弃用
    const res = await pending;
    expect(fetchSpy).toHaveBeenCalledTimes(2);
    expect(res).toMatchObject({ rows: rowsOf('g2'), catalogKnown: true });
  });

  it('fetch 失败且代际稳定 → catalogKnown=false(unknown fail-open 信任)', async () => {
    const res = await resolveSubmitGuardCatalog({
      ...baseArgs,
      fetch: () => Promise.reject(new Error('boom')),
    });
    expect(res).toMatchObject({ rows: [], catalogKnown: false });
  });

  it('fetch 失败但期间换代 → 重试 join 新代;第二次成功则采信', async () => {
    let gen = 1;
    const d1 = deferred<TestPayload>();
    const fetchSpy = vi.fn(() => (gen === 1 ? d1.promise : Promise.resolve(payload('g2'))));
    const pending = resolveSubmitGuardCatalog({ ...baseArgs, gen: () => gen, fetch: fetchSpy });
    await flush();
    expect(fetchSpy).toHaveBeenCalledTimes(1);
    gen = 2; // 换代后再失败 → 旧代失败不终止,重试新代
    d1.reject(new Error('boom'));
    const res = await pending;
    expect(fetchSpy).toHaveBeenCalledTimes(2);
    expect(res).toMatchObject({ rows: rowsOf('g2'), catalogKnown: true });
  });

  it('代际持续抖动(循环上限)→ 放弃校验,catalogKnown=false(信任既有绑定)', async () => {
    let gen = 1;
    const d = deferred<TestPayload>();
    const fetchSpy = vi.fn(() => {
      gen += 1; // 每次 await 期间都换代
      return d.promise;
    });
    const pending = resolveSubmitGuardCatalog({ ...baseArgs, gen: () => gen, fetch: fetchSpy });
    await flush();
    d.resolve(payload('stale'));
    const res = await pending;
    expect(fetchSpy).toHaveBeenCalledTimes(3); // 循环上限 3
    expect(res).toMatchObject({ rows: [], catalogKnown: false });
  });
});

describe('stored agent restore gating', () => {
  it('waits for the host new-task defaults before resolving a model', () => {
    // 被控电脑的默认还没读完:即使目录已就绪也不落定,否则会先落目录默认、读到的默认再也用不上。
    expect(canResolveStoredAgentRuntime({
      deviceId: 'mac',
      hostDefaultsSettled: false,
      hostRuntime: null,
      catalogReady: true,
      providersUnsupported: false,
    })).toBe(false);
  });

  it('waits while neither the catalog nor a host default for the agent is available', () => {
    expect(canResolveStoredAgentRuntime({
      deviceId: 'mac',
      hostDefaultsSettled: true,
      hostRuntime: null,
      catalogReady: false,
      providersUnsupported: false,
    })).toBe(false);
    expect(pickAgentDefaultRuntime({ providers: [],
      agentKind: 'claude-code',
      hostRuntime: null,
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: false,
    })).toMatchObject({ model: '', effort: 'medium' });
  });

  it('proceeds once the host gives a default for the agent', () => {
    expect(canResolveStoredAgentRuntime({
      deviceId: 'mac',
      hostDefaultsSettled: true,
      hostRuntime: hostRuntime('claude-code', 'claude-opus-5-5', { effort: 'high' }),
      catalogReady: false,
      providersUnsupported: false,
    })).toBe(true);
  });

  it('proceeds once the catalog is ready or explicitly unsupported, or without a device', () => {
    const base = { deviceId: 'mac', hostDefaultsSettled: true, hostRuntime: null };
    expect(canResolveStoredAgentRuntime({ ...base, catalogReady: true, providersUnsupported: false })).toBe(true);
    expect(canResolveStoredAgentRuntime({ ...base, catalogReady: false, providersUnsupported: true })).toBe(true);
    expect(canResolveStoredAgentRuntime({ ...base, deviceId: '', hostDefaultsSettled: false, catalogReady: false, providersUnsupported: false })).toBe(true);
  });

  it('reports a pending restore only for an unapplied stored agent on the target device', () => {
    const base = { expectedDeviceId: 'mac', selectedDeviceId: 'mac' };
    expect(isStoredAgentRestorePending({ ...base, storedAgentKind: 'claude-code', appliedStoredAgentKind: null })).toBe(true);
    expect(isStoredAgentRestorePending({ ...base, storedAgentKind: 'claude-code', appliedStoredAgentKind: 'claude-code' })).toBe(false);
    expect(isStoredAgentRestorePending({ ...base, storedAgentKind: null, appliedStoredAgentKind: null })).toBe(false);
    // 显式路由到别的设备时不恢复,自动默认照常工作。
    expect(isStoredAgentRestorePending({
      storedAgentKind: 'claude-code',
      appliedStoredAgentKind: null,
      expectedDeviceId: 'mac',
      selectedDeviceId: 'studio',
    })).toBe(false);
    expect(isStoredAgentRestorePending({
      storedAgentKind: 'codex',
      appliedStoredAgentKind: null,
      expectedDeviceId: '',
      selectedDeviceId: 'studio',
    })).toBe(true);
  });

  it('restores the remembered agent immediately and fills its model exactly once when data arrives (codex P1)', () => {
    // 事件序列:偏好到 → 数据未到 → 数据到 → 之后再有数据变化。
    let restored: StoredAgentRestoreState | null = null;
    const apply = (modelReady: boolean) => {
      const step = nextStoredAgentRestoreStep({ storedAgentKind: 'codex', restored, modelReady });
      if (step) restored = { agentKind: 'codex', phase: step === 'agent' ? 'agent' : 'done' };
      return step;
    };
    // 目录拉不到、也没有 Codex 最近任务:仍先恢复 agent(旧补丁在这里返回不恢复,草稿停在 Claude)。
    expect(apply(false)).toBe('agent');
    expect(apply(false)).toBeNull();
    expect(apply(true)).toBe('model');
    expect(apply(true)).toBeNull();
    expect(apply(false)).toBeNull();
  });

  it('restores agent and model together when data is already there, and restarts for a different remembered agent', () => {
    expect(nextStoredAgentRestoreStep({ storedAgentKind: 'pi', restored: null, modelReady: true })).toBe('full');
    expect(nextStoredAgentRestoreStep({
      storedAgentKind: 'pi',
      restored: { agentKind: 'codex', phase: 'done' },
      modelReady: false,
    })).toBe('agent');
  });

  it('gates the stored agent restore on real data and leaves the auto-default unblocked', () => {
    const source = newSessionSources;
    const storedStart = source.indexOf('const storedAgentKind = newSessionPreferences?.agentKind;');
    const autoStart = source.indexOf('const result = resolveNewSessionAutoDefault({');
    const storedSource = source.slice(storedStart, source.indexOf('storedAgentRestoreRef.current = restoreState', storedStart));
    const autoGuardSource = source.slice(source.lastIndexOf('useEffect(() => {', autoStart), autoStart);
    expect(storedSource).toContain('isStoredAgentRestorePending({');
    expect(storedSource).toContain('canResolveStoredAgentRuntime({');
    expect(storedSource).toContain('nextStoredAgentRestoreStep({');
    // model 步只补模型,不写 agent / 权限。
    const modelStep = source.slice(source.indexOf("if (step === 'model') {"), source.indexOf('const storedPermissionMode', storedStart));
    expect(modelStep).not.toContain('permissionMode');
    expect(modelStep).toContain('current.agentKind === storedAgentKind');
    expect(storedSource).not.toContain('deviceProviders.loading');
    // 恢复待落定时不阻断自动默认(Greptile P1)。
    expect(autoGuardSource).not.toContain('isStoredAgentRestorePending(');
  });

  it('reads and writes the host new-task defaults instead of inferring from task history', () => {
    const source = newSessionSources;
    // 读:与桌面远程新建同一读源,三个 agent 一次读齐。
    expect(source).toContain('return maker.getNewMakerDefaults(agentKind);');
    expect(source).toContain('return hostDraftRuntimeFromDefaults(defaults, agentKind);');
    // 写:本页的模型选择写回被控电脑;远程 Agent 的模型属于另一台电脑,不写回。
    expect(source).toMatch(/active: true,\s+markModelChoice: hostChoiceRequest\.markModelChoice,/);
    expect(source).toContain('if (!selectedDeviceId || remoteAgentChoice || !draft.model) return;');
    expect(source).not.toContain('pickMostRecentSessionRuntime');
    // 三个本机选择入口(供应商行 / 统一面板 / 旧端扁平列表)都写回。
    for (const name of ['selectProviderModelRow', 'selectUnifiedModel', 'selectFlatModel']) {
      const start = source.indexOf(`const ${name} = useCallback(`);
      const body = source.slice(start, source.indexOf('\n  }, [', start));
      expect(body, name).toContain('requestHostChoiceWrite(true);');
    }
    // 被控端刚启动回 {} 时有限次重读,不当成「从未选过模型」(Codex P1)。
    expect(source).toContain('if (defaults === undefined || isHostDraftDefaultsReady(defaults) || attempt >= 2) {');
    // 本页写回的选择优先于读取结果,晚到的旧读取不能把它覆盖(Codex P1)。
    const runtimeForStart = source.indexOf('const hostRuntimeFor = useCallback(');
    const runtimeForBody = source.slice(runtimeForStart, source.indexOf('\n  );', runtimeForStart));
    expect(runtimeForBody.indexOf('hostChoiceOverridesRef.current.get(deviceId)')).toBeLessThan(runtimeForBody.indexOf('current.byAgent[agentKind]'));
    // 切 agent 先等被控电脑默认读完再选模型,不把目录默认当成最终选择(Greptile P1)。
    const switchStart = source.indexOf('const switchAgent = useCallback(');
    const switchBody = source.slice(switchStart, source.indexOf('\n  }, [', switchStart));
    const waitAt = switchBody.indexOf('await waitHostDraftDefaults(selectedDeviceId, nextKind);');
    expect(waitAt).toBeGreaterThan(-1);
    expect(waitAt).toBeLessThan(switchBody.indexOf('pickAgentDefaultRuntime({'));
  });
});

describe('pickAgentDefaultRuntime on hosts without provider:list', () => {
  const flat = (id: string, marked: boolean): MobileModelOption => ({
    id, label: id, efforts: ['low', 'high'], effortDisplayNames: {}, defaultEffort: 'high', supportsFastMode: false,
    ...(marked ? { newSessionDefault: ['claude-code'] } : {}),
  } as MobileModelOption);

  it('uses the advertised capabilities model instead of settling an empty one', () => {
    const base = { agentKind: 'claude-code' as const, hostRuntime: null, modelRows: [], currentEffort: 'medium', catalogReady: false };
    expect(pickAgentDefaultRuntime({ providers: ((base).modelRows).map((row: ProviderModelRow) => row.provider), ...base, flatModels: [flat('a', false), flat('b', true)] }))
      .toMatchObject({ model: 'b', providerId: null, effort: 'high' });
    expect(pickAgentDefaultRuntime({ providers: ((base).modelRows).map((row: ProviderModelRow) => row.provider), ...base, flatModels: [flat('a', false)] })).toMatchObject({ model: 'a', providerId: null });
    // 能力表也没有时才留空。
    expect(pickAgentDefaultRuntime({ providers: ((base).modelRows).map((row: ProviderModelRow) => row.provider), ...base, flatModels: [] })).toMatchObject({ model: '' });
    expect(pickAgentDefaultRuntime({ ...base, providers: base.modelRows.map((row: ProviderModelRow) => row.provider) })).toMatchObject({ model: '' });
  });

  it('passes capabilities models only for unsupported hosts, on both stored-agent restore and agent switch', () => {
    const source = newSessionSources;
    expect(source).toContain('flatModels: flatModelsForUnsupportedHost(selectedDeviceId, storedAgentKind, deviceProvidersRef.current.unsupported),');
    expect(source).toContain('flatModels: flatModelsForUnsupportedHost(selectedDeviceId, nextKind, deviceProvidersRef.current.unsupported),');
    expect(source).toContain('if (!providersUnsupported || !deviceId) return undefined;');
  });
});

describe('isNewSessionRuntimePending', () => {
  const base = {
    settled: false,
    userTouched: false,
    remoteAgentPicked: false,
    selectedDeviceId: 'mac-studio',
    catalogReady: false,
    catalogFailed: false,
    modelRowCount: 0,
  };

  it('keeps the placeholder model pending until real data settles it', () => {
    expect(isNewSessionRuntimePending(base)).toBe(true);
    // 目录就绪但自动默认 / 恢复还没写入:仍是占位。
    expect(isNewSessionRuntimePending({ ...base, catalogReady: true, modelRowCount: 3 })).toBe(true);
    expect(isNewSessionRuntimePending({ ...base, settled: true })).toBe(false);
  });

  it('never blocks a choice the user made', () => {
    expect(isNewSessionRuntimePending({ ...base, userTouched: true })).toBe(false);
    expect(isNewSessionRuntimePending({ ...base, remoteAgentPicked: true })).toBe(false);
  });

  it('falls back to the built-in model when no more data will arrive', () => {
    expect(isNewSessionRuntimePending({ ...base, selectedDeviceId: '' })).toBe(false);
    expect(isNewSessionRuntimePending({ ...base, catalogFailed: true })).toBe(false);
    expect(isNewSessionRuntimePending({ ...base, catalogReady: true, modelRowCount: 0 })).toBe(false);
  });

  it('rolls back the restore marker and device lock when an automatic write is dropped', () => {
    const source = newSessionSources;
    const storedStart = source.indexOf('const storedAgentKind = newSessionPreferences?.agentKind;');
    const storedEffect = source.slice(storedStart, source.indexOf('}, [', storedStart));
    expect(storedEffect).toContain('if (storedAgentRestoreRef.current === restoreState) storedAgentRestoreRef.current = previousRestore;');
    expect(storedEffect).toContain('autoDefaultDeviceRef.current = previousAutoDefaultDevice;');
    const autoStart = source.indexOf('const result = resolveNewSessionAutoDefault({');
    const autoEffect = source.slice(autoStart, source.indexOf('}, [', autoStart));
    expect(autoEffect).toContain('autoDefaultDeviceRef.current = previousAutoDefaultDevice;');
  });

  it('binds the settled model to the computer it was settled for', () => {
    const source = newSessionSources;
    // 切到另一台电脑后重新等待,不能沿用上一台电脑落定的模型直接创建。
    expect(source).toContain('settled: !!selectedDeviceId && runtimeSettledDeviceId === selectedDeviceId,');
    expect(source).toContain("settleRuntime('stored-agent', deviceAtTrigger);");
    expect(source).toContain("settleRuntime('stored-agent-model', selectedDeviceId);");
    expect(source).toContain('result.appliedDeviceId);');
  });

  it('drops the previous computer\'s auto-picked model on device switch and gates goal creation too', () => {
    const source = newSessionSources;
    const selectStart = source.indexOf('const selectDevice = useCallback(');
    const selectDevice = source.slice(selectStart, source.indexOf('const handleBack = useCallback(', selectStart));
    // 用户没手动选过模型时清掉旧电脑的自动选择并重新等待;手动选过的保留。
    expect(selectDevice).toContain('option.deviceId !== selectedDeviceIdRef.current && !userTouchedRuntimeRef.current');
    expect(selectDevice).toContain('autoDefaultDeviceRef.current = null;');
    expect(selectDevice).toContain('setRuntimeSettledDeviceId(null);');
    expect(selectDevice).toContain("...(clearAutoRuntime ? { model: '', providerId: null, fastMode: false } : {}),");
    // 目标模式是独立创建入口:表单禁用 + 函数内兜底。
    const goalStart = source.indexOf('const createGoalSession = useCallback(');
    expect(source.slice(goalStart, goalStart + 400)).toContain('if (runtimePendingRef.current) return;');
    expect(source).toContain('disabled={worktreeCreateBlocked || runtimePending}');
  });

  it('aborts creation instead of sending an empty model after the submit-time catalog check', () => {
    expect(() => assertSubmitModelResolved({ model: 'claude-opus-5-5' }, 'claude-opus-5-5')).not.toThrow();
    expect(() => assertSubmitModelResolved({ model: '' }, 'delisted-model'))
      .toThrow('delisted-model 在这台电脑上已不可用,请重新选择模型后再发送。');
    // 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');
  });
});

describe('pickAgentDefaultRuntime', () => {
  it('follows the host new-task default of the target agent (model + effort reconciled)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'high' }),
      modelRows: [modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 历史坏数据自愈(copilot P2):providerId 空但目录有同名行 → 补全为该行 provider
    expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'high', providerId: 'prov-gpt-5.4' });
  });

  it('reconciles the recent effort down to the model default when unsupported', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('gpt-5.4', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'xhigh' }),
      modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 历史坏数据自愈(copilot P2):providerId 空但目录有同名行 → 补全为该行 provider
    expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'low', providerId: 'prov-gpt-5.4' });
  });

  it('omits the effort when the catalog is ready but the model has no row (delisted → omit, codex P2)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('gpt-5.4', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'gpt-legacy', { effort: 'high' }),
      modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 目录就绪且无匹配行 → 省略 effort(旧自定义档位对内置默认无效,由被控端取默认)
    expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-legacy', effort: '', providerId: null });
  });

  it('keeps the recent effort while the catalog is not ready (no authoritative section model yet)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: [],
      agentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'gpt-legacy', { effort: 'high' }),
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: false,
    });
    // 目录未就绪 → 保留最近任务 effort(未知不得省略,信任既有绑定)
    expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-legacy', effort: 'high', providerId: null });
  });

  it('inherits the recent session providerId when that provider still offers the model (#1898)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deepseek-v4-flash' }),
      modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'deepseek-v4-flash', effort: 'medium', providerId: 'prov-deepseek-v4-flash' });
  });

  it('reroutes to another connected provider offering the same model when the recent provider is gone (codex P1)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deleted' }),
      modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 来源失效但仍有其他来源提供同模型 → 顶替为该来源,模型照用(不留裸模型回落默认网关)
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'deepseek-v4-flash', effort: 'medium', providerId: 'prov-deepseek-v4-flash' });
  });

  it('reroutes by agent default rule when the recent provider is gone and multiple sources offer the model (codex P2)', () => {
    // 显式来源失效 + 同名模型多来源:不得取目录首行(custom 排前面)——按 agent
    // 默认规则解析(effectiveSourceIdForModel,codex 优先 openai 其次 xd),与
    // null 分支/模型面板高亮同口径,避免悄然改用另一套凭证/计费/Fast 语义。
    const fullRow = (providerId: string, connected = true): ProviderModelRow => ({
      provider: {
        id: providerId,
        name: providerId,
        agents: ['codex'],
        routing: { codex: {} },
        connected,
        models: { codex: [{ id: 'gpt-5.4', name: 'gpt-5.4' }] },
      } as unknown as ProviderModelRow['provider'],
      model: {
        id: 'gpt-5.4',
        displayName: 'gpt-5.4',
        efforts: ['low', 'medium'],
        defaultEffort: 'medium',
        contextWindow: 0,
      },
    });
    expect(
      resolveRecentModelAndProvider([fullRow('custom'), fullRow('xd')], { model: 'gpt-5.4', providerId: 'prov-deleted' }, 'codex', true, ([fullRow('custom'), fullRow('xd')]).map((row: ProviderModelRow) => row.provider)
      ),
    ).toEqual({ model: 'gpt-5.4', providerId: 'xd' });
    // 全部来源不可路由(未连接)→ 解析不到 → 落目录首项(整体回退)
    expect(
      resolveRecentModelAndProvider([fullRow('custom', false), fullRow('xd', false)], { model: 'gpt-5.4', providerId: 'prov-deleted' }, 'codex', true, ([fullRow('custom', false), fullRow('xd', false)]).map((row: ProviderModelRow) => row.provider)
      ),
    ).toEqual({ model: 'gpt-5.4', providerId: 'custom' });
  });

  it('falls back to the catalog top row (with its provider) when no provider offers the recent model', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low'), modelRow('claude-haiku', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'delisted-model', { providerId: 'prov-deleted' }),
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low'), modelRow('claude-haiku', ['low'], 'low')],
      currentEffort: 'high',
      catalogReady: true,
    });
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'claude-sonnet-4-6', effort: 'medium', providerId: 'prov-claude-sonnet-4-6' });
  });

  it('leaves the model empty with the default route when the catalog is ready but empty and the provider is gone', () => {
    const runtime = pickAgentDefaultRuntime({ providers: [],
      agentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'delisted-model', { providerId: 'prov-deleted' }),
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 回退内置默认且目录为空 → 省略 effort(codex P2:旧自定义档位对内置模型无效)
    expect(runtime).toEqual({ agentKind: 'codex', model: '', effort: '', providerId: null });
  });

  it('trusts the recent providerId while modelRows are still loading (empty)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: [],
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'deepseek' }),
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: false,
    });
    expect(runtime.providerId).toBe('deepseek');
  });

  it('falls back the model together when the catalog is ready but empty (loaded ≠ loading, codex P1)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: [],
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'deepseek' }),
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 目录就绪但为空:来源失效且无人能提供该模型 → model 一并回退内置默认(不留裸模型)
    // + 省略 effort(codex P2:旧自定义档位对内置模型无效)
    expect(runtime).toEqual({ agentKind: 'claude-code', model: '', effort: '', providerId: null });
  });

  it('reconciles effort with the exact (providerId, modelId) row when multiple providers offer the same model (Copilot)', () => {
    const shared = (providerId: string, efforts: readonly string[], defaultEffort: string): ProviderModelRow => ({
      provider: { id: providerId, name: providerId } as ProviderModelRow['provider'],
      model: {
        id: 'shared-model',
        displayName: 'shared-model',
        efforts: efforts as ProviderModelRow['model']['efforts'],
        defaultEffort: defaultEffort as ProviderModelRow['model']['defaultEffort'],
        contextWindow: 0,
      },
    });
    const runtime = pickAgentDefaultRuntime({ providers: ([shared('provA', ['low'], 'low'), shared('provB', ['high', 'xhigh'], 'high')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'shared-model', { effort: 'xhigh', providerId: 'provB' }),
      modelRows: [shared('provA', ['low'], 'low'), shared('provB', ['high', 'xhigh'], 'high')],
      currentEffort: 'medium',
      catalogReady: true,
    });
    // 若误用 provA 的 SectionModel,xhigh 会被降档为 low;精确匹配 provB 行则保留
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'shared-model', effort: 'xhigh', providerId: 'provB' });
  });

  it('keeps the recent effort untouched when the catalog is not ready and only a stale same-model row exists (codex P2)', () => {
    const shared = (providerId: string, efforts: readonly string[], defaultEffort: string): ProviderModelRow => ({
      provider: { id: providerId, name: providerId } as ProviderModelRow['provider'],
      model: {
        id: 'shared-model',
        displayName: 'shared-model',
        efforts: efforts as ProviderModelRow['model']['efforts'],
        defaultEffort: defaultEffort as ProviderModelRow['model']['defaultEffort'],
        contextWindow: 0,
      },
    });
    const runtime = pickAgentDefaultRuntime({ providers: ([shared('provA', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: hostRuntime('claude-code', 'shared-model', { effort: 'xhigh', providerId: 'provB' }),
      // 目录未就绪时的残留行:只有 provA 提供同 modelId,provB 不在其中
      modelRows: [shared('provA', ['low'], 'low')],
      currentEffort: 'medium',
      catalogReady: false,
    });
    // 目录未知 → 不得用残留 provA 行的档位表把 xhigh 降档;保留最近任务的 effort
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'shared-model', effort: 'xhigh', providerId: 'provB' });
  });

  it('falls back to the top of the target agent\'s model list when the host default belongs to another agent', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('gpt-5.4', ['low', 'medium'], 'low'), modelRow('gpt-mini', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'codex',
      hostRuntime: hostRuntime('claude-code', 'claude-opus-4-8'),
      modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low'), modelRow('gpt-mini', ['low'], 'low')],
      currentEffort: 'high', // 不被目标模型支持 → reconcile 到默认 'low'
      catalogReady: true,
    });
    expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'low', providerId: 'prov-gpt-5.4' });
  });

  it('uses the regional default before the top row, including the explicit Pi v3 marker', () => {
    const rows = [
      modelRow('top', ['low'], 'low'),
      modelRow('cc-regional', ['medium'], 'medium', ['claude-code']),
      modelRow('pi-regional', ['high'], 'high', ['pi']),
    ];
    // 区域默认来自 provider 行 → 携带该行 provider(#1898 语义,merge main 后适配)
    expect(pickAgentDefaultRuntime({ providers: (rows).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: null,
      modelRows: rows,
      currentEffort: 'high',
      catalogReady: true,
    })).toEqual({ agentKind: 'claude-code', model: 'cc-regional', effort: 'medium', providerId: 'prov-cc-regional' });
    expect(pickAgentDefaultRuntime({ providers: (rows).map((row: ProviderModelRow) => row.provider),
      agentKind: 'pi',
      hostRuntime: null,
      modelRows: rows,
      currentEffort: 'high',
      catalogReady: true,
    })).toEqual({ agentKind: 'pi', model: 'pi-regional', effort: 'high', providerId: 'prov-pi-regional' });
  });

  it('uses only the explicit Pi regional default marker', () => {
    expect(pickAgentDefaultRuntime({ providers: ([
        modelRow('top', ['low'], 'low'),
        modelRow('pi-regional', ['high'], 'high', ['pi']),
      ]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'pi',
      hostRuntime: null,
      modelRows: [
        modelRow('top', ['low'], 'low'),
        modelRow('pi-regional', ['high'], 'high', ['pi']),
      ],
      currentEffort: 'medium',
      catalogReady: true,
    })).toEqual({
      agentKind: 'pi',
      model: 'pi-regional',
      effort: 'high',
      providerId: 'prov-pi-regional',
    });
  });

  it('keeps the marked provider row when another provider offers the same modelId earlier (codex P2)', () => {
    const shared = (providerId: string, marked: boolean, efforts: readonly string[], defaultEffort: string): ProviderModelRow => ({
      provider: { id: providerId, name: providerId } as ProviderModelRow['provider'],
      model: {
        id: 'shared-model',
        displayName: 'shared-model',
        efforts: efforts as ProviderModelRow['model']['efforts'],
        defaultEffort: defaultEffort as ProviderModelRow['model']['defaultEffort'],
        contextWindow: 0,
        ...(marked ? { newSessionDefault: ['claude-code'] } : {}),
      },
    });
    // [A/foo(无标记), B/foo(标记)]:必须在行层面选中 B,携带 B 的来源并按其档位表校准
    const runtime = pickAgentDefaultRuntime({ providers: ([shared('provA', false, ['low'], 'low'), shared('provB', true, ['high', 'xhigh'], 'high')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'claude-code',
      hostRuntime: null,
      modelRows: [shared('provA', false, ['low'], 'low'), shared('provB', true, ['high', 'xhigh'], 'high')],
      currentEffort: 'high',
      catalogReady: true,
    });
    expect(runtime).toEqual({ agentKind: 'claude-code', model: 'shared-model', effort: 'high', providerId: 'provB' });
  });

  it('leaves the model empty and omits effort when the catalog is ready but empty (codex P2)', () => {
    expect(pickAgentDefaultRuntime({ providers: [],
      agentKind: 'codex',
      hostRuntime: null,
      modelRows: [],
      currentEffort: 'medium',
      catalogReady: true,
    })).toEqual({ agentKind: 'codex', model: '', effort: '', providerId: null });
    expect(pickAgentDefaultRuntime({ providers: [],
      agentKind: 'claude-code',
      hostRuntime: null,
      modelRows: [],
      currentEffort: 'high',
      catalogReady: true,
    })).toEqual({ agentKind: 'claude-code', model: '', effort: '', providerId: null });
  });

  it('skips the top-row branch while the catalog is not ready (stale rows from the previous device, codex P1)', () => {
    const runtime = pickAgentDefaultRuntime({ providers: ([modelRow('gpt-5.4', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      agentKind: 'codex',
      hostRuntime: null,
      modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
      currentEffort: 'medium',
      catalogReady: false,
    });
    // 目录未就绪 → 不抄残留目录的首项,落内置默认 + 默认路由
    expect(runtime).toEqual({ agentKind: 'codex', model: '', effort: 'medium', providerId: null });
    expect(runtime.providerId).toBeNull();
  });

  it('resolves the default source by agent rule for a null providerId offered by multiple sources (codex review P2)', () => {
    // 同名模型由多个来源提供时,不得取目录首行(anthropic 在前)——被控端默认路由
    // 按 agent 解析(effectiveSourceIdForModel,codex 优先 openai 其次 xd),UI 高亮与
    // 创建路由必须一致;解析不到时保留 null 默认路由。
    const fullRow = (providerId: string, connected = true): ProviderModelRow => ({
      provider: {
        id: providerId,
        name: providerId,
        agents: ['codex'],
        routing: { codex: {} },
        connected,
        models: { codex: [{ id: 'gpt-5.4', name: 'gpt-5.4' }] },
      } as unknown as ProviderModelRow['provider'],
      model: {
        id: 'gpt-5.4',
        displayName: 'gpt-5.4',
        efforts: ['low', 'medium'],
        defaultEffort: 'medium',
        contextWindow: 0,
      },
    });
    expect(
      resolveRecentModelAndProvider([fullRow('anthropic'), fullRow('xd')], { model: 'gpt-5.4', providerId: null }, 'codex', true, ([fullRow('anthropic'), fullRow('xd')]).map((row: ProviderModelRow) => row.provider)
      ),
    ).toEqual({ model: 'gpt-5.4', providerId: 'xd' });
    // 全部来源不可路由(未连接)→ 解析不到 → 保留 null 默认路由,不固化任何来源
    expect(
      resolveRecentModelAndProvider([fullRow('anthropic', false), fullRow('xd', false)], { model: 'gpt-5.4', providerId: null }, 'codex', true, ([fullRow('anthropic', false), fullRow('xd', false)]).map((row: ProviderModelRow) => row.provider)
      ),
    ).toEqual({ model: 'gpt-5.4', providerId: null });
  });

  it('Auto 只按模型 ID 认:服务端把它挪到另一家 Cindy 来源后跟过去,不落到用户自己接的供应商', () => {
    const autoRow = (
      providerId: string,
      source: 'builtin' | 'organization' | 'user',
      modelIds: readonly string[],
      modelId: string,
    ): ProviderModelRow => ({
      provider: {
        id: providerId,
        name: providerId,
        source,
        agents: ['pi'],
        routing: { pi: {} },
        connected: true,
        models: { pi: modelIds.map((id) => ({ id, name: id })) },
      } as unknown as ProviderModelRow['provider'],
      model: { id: modelId, displayName: modelId, efforts: [], defaultEffort: null, contextWindow: 0 },
    });
    const auto = 'auto/group-1';
    // 号池 → Cindy AI:记住的号池还在(有别的模型),但已不再提供这个 Auto。
    const toPlatform = [
      autoRow('custom', 'user', [auto], auto),
      autoRow('org-pool', 'organization', ['pool-model'], 'pool-model'),
      autoRow('xd', 'builtin', ['auto', auto], auto),
    ];
    expect(
      resolveRecentModelAndProvider(toPlatform, { model: auto, providerId: 'org-pool' }, 'pi', true, (toPlatform).map((row: ProviderModelRow) => row.provider)),
    ).toEqual({ model: auto, providerId: 'xd' });
    // Cindy AI → 号池:用户自己接的供应商排在前面也提供同 ID,不能被通用顶替规则选中。
    const toPool = [
      autoRow('custom', 'user', [auto], auto),
      autoRow('xd', 'builtin', ['auto'], 'auto'),
      autoRow('org-pool', 'organization', ['pool-model', auto], auto),
    ];
    expect(
      resolveRecentModelAndProvider(toPool, { model: auto, providerId: 'xd' }, 'pi', true, (toPool).map((row: ProviderModelRow) => row.provider)),
    ).toEqual({ model: auto, providerId: 'org-pool' });
    // PR #6355 Greptile P1:身份取完整目录,但隐藏的 Cindy AI 同名模型不能挤掉可见号池。
    // unit:旧号池无行,平台组 Auto 无行,自定义来源排在前面;仍选可见的新号池。
    const visible = [toPool[0], toPool[2]];
    const fullCatalog = [
      ...visible.map((row: ProviderModelRow) => row.provider),
      autoRow('old-pool', 'organization', [], 'unused').provider,
      autoRow('xd', 'builtin', [auto], auto).provider,
    ];
    expect(
      resolveRecentModelAndProvider(visible, { model: auto, providerId: 'old-pool' }, 'pi', true, fullCatalog, undefined),
    ).toEqual({ model: auto, providerId: 'org-pool' });
    // 负向:用户自己接的供应商仍提供同名 auto/... 时原样保留,不被拉去 Cindy 来源。
    expect(
      resolveRecentModelAndProvider(toPlatform, { model: auto, providerId: 'custom' }, 'pi', true, (toPlatform).map((row: ProviderModelRow) => row.provider)),
    ).toEqual({ model: auto, providerId: 'custom' });
    // 负向:Auto 从两份目录都消失时不崩,按既有规则落到目录首项。
    const gone = [
      autoRow('xd', 'builtin', ['auto'], 'auto'),
      autoRow('org-pool', 'organization', ['pool-model'], 'pool-model'),
    ];
    expect(
      resolveRecentModelAndProvider(gone, { model: auto, providerId: 'org-pool' }, 'pi', true, (gone).map((row: ProviderModelRow) => row.provider)),
    ).toEqual({ model: 'auto', providerId: 'xd' });
  });
});

describe('resolveNewSessionAutoDefault', () => {
  const baseInput = {
    userTouched: false,
    appliedDeviceId: null as string | null,
    selectedDeviceId: 'devA',
    hostDefaultsSettled: true,
    hostRuntime: null as NewSessionRuntime | null,
    modelRows: [] as ProviderModelRow[],
    rowsAgentKind: 'claude-code' as const,
    catalogReady: true,
    availableModels: [],
    currentEffort: 'medium',
  };

  it('intent ⓪: waits until the host new-task defaults are read (no premature catalog default)', () => {
    expect(resolveNewSessionAutoDefault({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      hostDefaultsSettled: false,
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')],
    })).toBeNull();
  });

  it('intent ①: follows the host new-task default of the current agent (model + effort reconciled, agent untouched)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      rowsAgentKind: 'codex',
      hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'high' }),
      modelRows: [modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')],
    });
    // 历史坏数据自愈(copilot P2):providerId 空但目录有同名行 → 补全为该行 provider
    expect(result).toEqual({
      appliedDeviceId: 'devA',
      source: 'host-default',
      patch: {
        model: 'gpt-5.4',
        effort: 'high',
        providerId: 'prov-gpt-5.4',
      },
    });
  });

  it('intent ①a: a host default is the only default — task history no longer steers it', () => {
    // 回归:自动化 / 测试任务(从未由用户发消息)曾因更新时间最新被当成「最近使用」,
    // 把新建任务默认带成 Haiku。现在没有被控电脑默认时只看目录区域默认。
    const result = resolveNewSessionAutoDefault({ providers: ([
        modelRow('claude-haiku-4-5', ['high'], 'high'),
        modelRow('claude-opus-5-5', ['high'], 'high', ['claude-code']),
      ]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      modelRows: [
        modelRow('claude-haiku-4-5', ['high'], 'high'),
        modelRow('claude-opus-5-5', ['high'], 'high', ['claude-code']),
      ],
    });
    expect(result).toMatchObject({ source: 'catalog-default', patch: { model: 'claude-opus-5-5' } });
  });

  it('intent ①+: inherits the host default providerId when the provider still offers the model (#1898)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deepseek-v4-flash' }),
      modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')],
    });
    expect(result?.patch).toMatchObject({
      model: 'deepseek-v4-flash',
      providerId: 'prov-deepseek-v4-flash',
    });
  });

  it('intent ①-: reroutes to another provider offering the same model when the host default provider is gone (codex P1)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-gone' }),
      modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')],
    });
    expect(result?.patch).toMatchObject({
      model: 'deepseek-v4-flash',
      providerId: 'prov-deepseek-v4-flash',
    });
  });

  it('intent ①-fallback: falls back to the catalog top row when no provider offers the host default model', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      hostRuntime: hostRuntime('claude-code', 'delisted-model', { providerId: 'prov-gone' }),
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')],
    });
    expect(result?.patch).toMatchObject({
      model: 'claude-sonnet-4-6',
      providerId: 'prov-claude-sonnet-4-6',
    });
  });

  it('intent ①z: ignores a host default that belongs to another agent than the rows', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      rowsAgentKind: 'claude-code',
      hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'xhigh', providerId: 'prov-codex-only' }),
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'medium')],
    });
    expect(result).toMatchObject({ source: 'catalog-default', patch: { model: 'claude-sonnet-4-6' } });
  });

  it('intent ①r: reconciles the host default effort against the matched row ladder', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { effort: 'xhigh', providerId: 'prov-deepseek-v4-flash' }),
      modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
    });
    expect(result?.patch).toMatchObject({
      model: 'deepseek-v4-flash',
      effort: 'medium', // xhigh 不在该 agent 目录档位表 → reconcile 到模型默认档
      providerId: 'prov-deepseek-v4-flash',
    });
  });

  it('intent ②: no host default → top of the model list (model + reconciled effort + row provider, agentKind untouched)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low'), modelRow('claude-haiku', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      currentEffort: 'high', // 不被首个模型支持 → reconcile 到默认 'low'
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low'), modelRow('claude-haiku', ['low'], 'low')],
    });
    expect(result).toEqual({
      appliedDeviceId: 'devA',
      source: 'catalog-default',
      patch: { model: 'claude-sonnet-4-6', effort: 'low', providerId: 'prov-claude-sonnet-4-6' },
    });
    expect(result?.patch).not.toHaveProperty('agentKind');
  });

  it('intent ②-wait: catalog not ready → do not copy the (stale) top row, wait for the real catalog (codex P1)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      catalogReady: false,
      modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')],
    });
    expect(result).toBeNull();
  });

  it('intent ②a: no host default → regional default before the top row (upstream main 移植)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ([
        modelRow('top', ['low'], 'low'),
        modelRow('regional', ['medium'], 'medium', ['claude-code']),
      ]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      currentEffort: 'high',
      modelRows: [
        modelRow('top', ['low'], 'low'),
        modelRow('regional', ['medium'], 'medium', ['claude-code']),
      ],
    });
    // 区域默认来自 provider 行 → 携带该行 provider(#1898 语义)
    expect(result?.patch).toEqual({ model: 'regional', effort: 'medium', providerId: 'prov-regional' });
  });

  it('intent ②a: keeps the marked provider row when another provider offers the same modelId earlier (codex P2)', () => {
    const shared = (providerId: string, marked: boolean, efforts: readonly string[], defaultEffort: string): ProviderModelRow => ({
      provider: { id: providerId, name: providerId } as ProviderModelRow['provider'],
      model: {
        id: 'shared-model',
        displayName: 'shared-model',
        efforts: efforts as ProviderModelRow['model']['efforts'],
        defaultEffort: defaultEffort as ProviderModelRow['model']['defaultEffort'],
        contextWindow: 0,
        ...(marked ? { newSessionDefault: ['claude-code'] } : {}),
      },
    });
    const result = resolveNewSessionAutoDefault({ providers: ([shared('provA', false, ['low'], 'low'), shared('provB', true, ['high', 'xhigh'], 'high')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      currentEffort: 'high',
      modelRows: [shared('provA', false, ['low'], 'low'), shared('provB', true, ['high', 'xhigh'], 'high')],
    });
    // 同 modelId 多来源时必须在行层面选中带标记的 provB,并按其档位表校准 effort
    expect(result?.patch).toEqual({ model: 'shared-model', effort: 'high', providerId: 'provB' });
  });

  it('intent ②b: provider list unavailable → regional default from normalized capabilities (upstream main 移植)', () => {
    const result = resolveNewSessionAutoDefault({ providers: ((baseInput).modelRows).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      providersUnsupported: true,
      currentEffort: 'high',
      availableModels: [
        {
          id: 'regional',
          label: 'Regional',
          efforts: ['medium'],
          effortDisplayNames: {},
          defaultEffort: 'medium',
          supportsFastMode: false,
          newSessionDefault: ['claude-code'],
        },
      ],
    });
    // 扁平列表无 provider 行 → 默认路由
    expect(result?.patch).toEqual({ model: 'regional', effort: 'medium', providerId: null });
  });

  it('intent ③: switching device (not manually touched) recomputes for the new device', () => {
    expect(resolveNewSessionAutoDefault({ providers: ([modelRow('model-B', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput, hostRuntime: hostRuntime('claude-code', 'model-B'), appliedDeviceId: 'devA', selectedDeviceId: 'devB',
      modelRows: [modelRow('model-B', ['low'], 'low')],
    })?.patch).toMatchObject({ model: 'model-B' });
  });

  it('intent ④: userTouched → null (never overrides a manual selection)', () => {
    expect(resolveNewSessionAutoDefault({ providers: ([modelRow('gpt-5.4', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput,
      userTouched: true,
      hostRuntime: hostRuntime('claude-code', 'gpt-5.4'),
      modelRows: [modelRow('gpt-5.4', ['low'], 'low')],
    })).toBeNull();
  });

  it('returns null when modelRows are not ready yet and there is no host default (no premature set)', () => {
    expect(resolveNewSessionAutoDefault({ providers: [], ...baseInput, modelRows: [] })).toBeNull();
  });

  it('applies the capabilities flat default when the catalog is explicitly unavailable (old host without provider:list, codex P2)', () => {
    const result = resolveNewSessionAutoDefault({ providers: [],
      ...baseInput,
      hostRuntime: null,
      modelRows: [],
      catalogReady: false,
      providersUnsupported: true,
      availableModels: [
        {
          id: 'flat-default',
          label: 'Flat Default',
          efforts: ['medium'],
          effortDisplayNames: {},
          defaultEffort: 'medium',
          supportsFastMode: false,
          newSessionDefault: ['claude-code'],
        } as MobileModelOption,
      ],
    });
    // 目录明确不可用(旧被控端)→ 放行 capabilities 扁平回退;扁平列表无 provider 结构 → 默认路由
    expect(result).toEqual({
      appliedDeviceId: 'devA',
      source: 'catalog-default',
      patch: {
        model: 'flat-default',
        effort: 'medium',
        providerId: null,
      },
    });
  });

  it('does not fall back to flat defaults while the catalog is merely loading (error is empty, codex P2)', () => {
    expect(resolveNewSessionAutoDefault({ providers: [],
      ...baseInput,
      hostRuntime: null,
      modelRows: [],
      catalogReady: false,
      providersUnsupported: false,
      availableModels: [{
        id: 'flat-default', label: 'Flat Default', efforts: ['medium'], effortDisplayNames: {}, defaultEffort: 'medium', supportsFastMode: false, newSessionDefault: ['claude-code'],
      } as MobileModelOption],
    })).toBeNull();
  });

  it('returns null when this device was already applied, and when no device is selected', () => {
    expect(resolveNewSessionAutoDefault({ providers: ([modelRow('m', ['low'], 'low')]).map((row: ProviderModelRow) => row.provider),
      ...baseInput, appliedDeviceId: 'devA', modelRows: [modelRow('m', ['low'], 'low')],
    })).toBeNull();
    expect(resolveNewSessionAutoDefault({ providers: ((baseInput).modelRows).map((row: ProviderModelRow) => row.provider), ...baseInput, selectedDeviceId: '' })).toBeNull();
  });
});

describe('pickNewSessionDefaultDevice', () => {
  const devices = [
    { deviceId: 'devA', name: 'Mac A' },
    { deviceId: 'devB', name: 'Mac B' },
  ];

  it('uses the stored device when the route device is only a default candidate', () => {
    expect(pickNewSessionDefaultDevice({
      deviceOptions: devices,
      preferredDeviceId: 'devB',
      routeDevice: devices[0],
      routeDeviceExplicit: false,
    })).toEqual(devices[1]);
  });

  it('keeps an explicit route device over stored preferences', () => {
    expect(pickNewSessionDefaultDevice({
      deviceOptions: devices,
      preferredDeviceId: 'devB',
      routeDevice: devices[0],
      routeDeviceExplicit: true,
    })).toEqual(devices[0]);
  });

  it('falls back to the route device, then the first available device', () => {
    expect(pickNewSessionDefaultDevice({
      deviceOptions: devices,
      preferredDeviceId: 'missing',
      routeDevice: devices[0],
      routeDeviceExplicit: false,
    })).toEqual(devices[0]);

    expect(pickNewSessionDefaultDevice({
      deviceOptions: devices,
      routeDevice: null,
      routeDeviceExplicit: false,
    })).toEqual(devices[0]);
  });
});

// 接线锁(house style 的 source 断言,同下方 composer surface 测试):
// pickNewSessionDefaultDevice 的优先级行为已由上面的纯函数单测覆盖,这里只锁两个屏幕
// 之间 deviceExplicit 路由参数的存在性——用全文件唯一字符串断言,不做函数体切片定位,
// 避免锚点(如 deps 数组)变化时 indexOf 失效产生误导性报错。
describe('new session default device follows the home device filter', () => {
  it('sends deviceExplicit for a home device filter or a checked recommendation target', () => {
    const homeSource = readTextLf(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
    // 筛选电脑或推荐指定电脑时带显式标记;普通新建保留记忆回落。
    expect(homeSource).toContain("...(selectedDeviceId || explicitDeviceId ? { deviceExplicit: '1' } : {})");
  });

  it('treats the deviceExplicit route flag as an explicit device on the new-session screen', () => {
    const newSource = newSessionSources;
    expect(newSource).toContain('deviceExplicit?: string;');
    expect(newSource).toContain("readRouteString(params.deviceExplicit) === '1'");
  });
});

describe('new session model', () => {
  const DRAFT_WITH_MODEL = { ...DEFAULT_NEW_SESSION_DRAFT, model: 'claude-sonnet-4-6' };

  it('hides dot directories by default and restores them when enabled', () => {
    const entries = [
      { name: '.config', kind: 'dir' as const, path: '/Users/cindy/.config' },
      { name: '.workspace', kind: 'symlink' as const, path: '/Users/cindy/.workspace' },
      { name: 'Code', kind: 'dir' as const, path: '/Users/cindy/Code' },
    ];

    expect(filterRemoteDirectoryEntries(entries, false).map((entry) => entry.name)).toEqual(['Code']);
    expect(filterRemoteDirectoryEntries(entries, true)).toEqual(entries);
  });

  it('normalizes Windows drive options from fs:list-dir and hides the switch without a second drive', () => {
    // 盘符根是被控端 host-native 的 Windows wire 格式,固定写反斜杠。
    expect(normalizeRemoteDirectoryDrives([
      { name: 'C:', path: 'C:\\', current: false },
      { name: 'D:', path: 'D:\\', current: true },
      { path: 'E:\\' },
      { name: 'dup', path: 'D:\\', current: false },
      { name: 'bad' },
      null,
    ])).toEqual([
      { name: 'C:', path: 'C:\\', current: false },
      { name: 'D:', path: 'D:\\', current: true },
      { name: 'E:\\', path: 'E:\\', current: false },
    ]);
    expect(normalizeRemoteDirectoryDrives([{ name: 'C:', path: 'C:\\', current: true }])).toEqual([]);
    expect(normalizeRemoteDirectoryDrives(undefined)).toEqual([]);
    expect(normalizeRemoteDirectoryDrives('C:')).toEqual([]);
  });

  it('drops in-flight remote browse results after switching computers, even if the sequence still matches', () => {
    expect(isCurrentRemoteBrowseRequest(
      { seq: 3, deviceId: 'pc-a' },
      { seq: 3, deviceId: 'pc-b' },
    )).toBe(false);
    expect(isCurrentRemoteBrowseRequest(
      { seq: 3, deviceId: 'pc-a' },
      { seq: 4, deviceId: 'pc-a' },
    )).toBe(false);
    expect(isCurrentRemoteBrowseRequest(
      { seq: 3, deviceId: 'pc-a' },
      { seq: 3, deviceId: 'pc-a' },
    )).toBe(true);
    expect(isCurrentRemoteBrowseRequest(
      { seq: 3, deviceId: '' },
      { seq: 3, deviceId: '' },
    )).toBe(false);

    const newSource = newSessionSources;
    expect(newSource).toContain('browseSeqRef.current += 1');
    expect(newSource).toContain('selectedDeviceIdRef.current = option.deviceId');
    expect(newSource).toContain('isCurrentRemoteBrowseRequest');
  });

  it('retries the current directory when Windows drive enumeration is still pending', () => {
    expect(shouldRetryRemoteBrowseDrives(true, 0)).toBe(true);
    expect(shouldRetryRemoteBrowseDrives(true, 2)).toBe(true);
    expect(shouldRetryRemoteBrowseDrives(true, 3)).toBe(false);
    expect(shouldRetryRemoteBrowseDrives(false, 0)).toBe(false);
    expect(shouldRetryRemoteBrowseDrives(undefined, 0)).toBe(false);

    const newSource = newSessionSources;
    expect(newSource).toContain('shouldRetryRemoteBrowseDrives');
    expect(newSource).toContain('result.drivesPending');
  });

  it('keeps the Android drive pill at 34pt and wraps it in a 44pt hit target', () => {
    const newSource = newSessionSources;
    expect(newSource).toContain('styles.browseDriveHit');
    expect(newSource).toMatch(/browseDriveHit:\s*\{[^}]*minHeight:\s*44/);
    expect(newSource).toMatch(/browseDriveHit:\s*\{[^}]*minWidth:\s*44/);
  });

  it('builds device-link create-session args with desktop remote-project semantics', () => {
    expect(buildRemoteCreateSessionOptions({
      ...DRAFT_WITH_MODEL,
      workingDir: ' /repo/xdt-maker ',
      firstMessage: 'hello',
      extraDirs: [' /repo/docs ', '/repo/docs', ''],
    })).toEqual({
      agentKind: 'claude-code',
      workingDir: '/repo/xdt-maker',
      workspaceKind: 'project',
      model: 'claude-sonnet-4-6',
      effort: 'medium',
      permissionMode: 'auto',
      fastMode: false,
      extraDirs: ['/repo/docs'],
    });
  });

  it('runs the Agent on the picked remote computer or share', () => {
    const draft = { ...DRAFT_WITH_MODEL, workingDir: '/repo/app', firstMessage: 'hi' };
    expect(applyRemoteAgentPick(draft, null)).toBe(draft);
    const remote = applyRemoteAgentPick(draft, {
      deviceId: 'share:s1', agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', effort: 'high', fastMode: true,
    });
    expect(remote).toMatchObject({
      agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', effort: 'high', fastMode: true,
      agentDeviceId: 'share:s1', workingDir: '/repo/app', firstMessage: 'hi',
    });
    expect(buildRemoteCreateSessionOptions(remote)).toMatchObject({
      agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', agentDeviceId: 'share:s1',
    });
    expect(buildRemoteCreateSessionOptions(draft)).not.toHaveProperty('agentDeviceId');
    // 乐观会话行一开始就带上 Agent 所在电脑,会话页按那台的目录显示模型。
    expect(sessionFromCreateResult({ sessionId: 's' }, remote).agentDeviceId).toBe('share:s1');
    expect(sessionFromCreateResult({ sessionId: 's' }, draft)).not.toHaveProperty('agentDeviceId');
  });

  it('builds folderless dialogue create-session args for controlled-side cwd allocation', () => {
    expect(buildRemoteCreateSessionOptions({
      ...DRAFT_WITH_MODEL,
      workspaceKind: 'dialogue',
      workingDir: ' /repo/should-not-leak ',
      firstMessage: 'hello',
      extraDirs: ['/repo/docs'],
    })).toEqual({
      agentKind: 'claude-code',
      workspaceKind: 'dialogue',
      model: 'claude-sonnet-4-6',
      effort: 'medium',
      permissionMode: 'auto',
      fastMode: false,
    });
  });

  it('omits effort from create-session args when the selected model has no effort control', () => {
    expect(buildRemoteCreateSessionOptions({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo/xdt-maker',
      firstMessage: 'hello',
      model: 'claude-haiku-4-6',
      effort: '',
    })).toEqual({
      agentKind: 'claude-code',
      workingDir: '/repo/xdt-maker',
      workspaceKind: 'project',
      model: 'claude-haiku-4-6',
      permissionMode: 'auto',
      fastMode: false,
    });
  });

  it('preserves a Codex Auto-review draft when creating the session', () => {
    expect(buildRemoteCreateSessionOptions({
      ...DRAFT_WITH_MODEL,
      agentKind: 'codex',
      model: 'gpt-5.4',
      permissionMode: 'auto',
      workingDir: '/repo/xdt-maker',
    })).toMatchObject({
      agentKind: 'codex',
      permissionMode: 'auto',
    });
  });

  it('switches agent defaults without carrying a Claude model into Codex', () => {
    const codex = withAgentDefaults(DRAFT_WITH_MODEL, 'codex');
    expect(codex).toMatchObject({
      agentKind: 'codex',
      model: '',
      permissionMode: 'auto',
    });

    const claude = withAgentDefaults({ ...codex, fastMode: true }, 'claude-code');
    expect(claude).toMatchObject({
      agentKind: 'claude-code',
      model: '',
      permissionMode: 'auto',
      fastMode: false,
    });
  });

  it('exposes Pi as a first-class agent and preserves Fast for Pi sessions', () => {
    expect(NEW_SESSION_AGENT_OPTIONS.map((option) => option.kind)).toEqual([
      'claude-code', 'codex', 'pi',
    ]);
    const pi = withAgentDefaults({ ...DRAFT_WITH_MODEL, fastMode: true }, 'pi');
    expect(pi).toMatchObject({ agentKind: 'pi', model: '', fastMode: true });
    expect(buildRemoteCreateSessionOptions({
      ...pi,
      workingDir: '/repo/xdt-maker',
      firstMessage: 'hello',
    })).toMatchObject({ agentKind: 'pi', fastMode: true });
  });

  it('filters the new-session agent options by the controlled device runtime-registered set', () => {
    // null(未拉到)→ fail-open,全部保留。
    expect(availableNewSessionAgentOptions(null).map((o) => o.kind)).toEqual([
      'claude-code', 'codex', 'pi',
    ]);
    // 被控端无 Pi(二进制缺失)→ 隐藏 Pi,避免建出 requireAgent 报 not-registered 的会话。
    expect(
      availableNewSessionAgentOptions(new Set(['claude-code', 'codex'])).map((o) => o.kind),
    ).toEqual(['claude-code', 'codex']);
    // 只有 Pi 注册(理论)→ 只留 Pi。
    expect(availableNewSessionAgentOptions(new Set(['pi'])).map((o) => o.kind)).toEqual(['pi']);
    // 空集(被控端异常)→ 退回至少 Claude,不把入口清空到无法创建。
    expect(availableNewSessionAgentOptions(new Set()).map((o) => o.kind)).toEqual(['claude-code']);
  });

  it('wires the new-session screen to gate agents by list-available-agents and coerce off unavailable', () => {
    const newSource = newSessionSources;
    // 拉被控端 runtime 注册集合,渲染按可用集过滤,选中不可用时 coerce。
    expect(newSource).toContain('maker.listAvailableAgents()');
    expect(newSource).toContain('onAgentsChanged');
    expect(newSource).toContain('evictAgentCapabilitiesForDevice(deviceId);');
    expect(newSource).toContain('const rosterRecoveryIdentityRef = useRef<');
    expect(newSource).toContain('setAvailableAgentRosterRefreshNonce((value) => value + 1);');
    expect(newSource).toContain('previous.connectionEpoch === connectionEpoch');
    expect(newSource.match(/subscribe\(`new-session:\$\{selectedDeviceId\}`/g)?.length ?? 0).toBeGreaterThanOrEqual(2);
    expect(newSource).toContain('availableNewSessionAgentOptions(availableAgentKinds).map');
    expect(newSource).toMatch(/availableAgentKinds\.has\(draft\.agentKind\)/);
    // 传输层 passthrough 到 allowlisted channel。
    const transportSource = readTextLf(
      resolve(process.cwd(), 'src/device-link/mobileMakerTransport.ts'), 'utf8');
    expect(transportSource).toContain("listAvailableAgents: () => call('maker:list-available-agents', [])");
  });

  it('uses safe per-agent permission defaults for new interactive sessions', () => {
    expect(defaultPermissionModeForNewSessionAgent('claude-code')).toBe('auto');
    expect(defaultPermissionModeForNewSessionAgent('codex')).toBe('auto');
  });

  it('validates required path, model and first-message payload', () => {
    expect(validateNewSessionDraft(DEFAULT_NEW_SESSION_DRAFT)).toBe('请输入电脑端项目路径。');
    // 草稿初值不写死模型:由最近任务 / 目录落定,拿不到时留空让用户选。
    expect(DEFAULT_NEW_SESSION_DRAFT.model).toBe('');
    expect(validateNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workspaceKind: 'dialogue',
    })).toBe('请输入首条消息或添加附件。');
    expect(validateNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo',
      model: '',
    })).toBe('请输入模型。');
    expect(validateNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo',
      firstMessage: '',
    })).toBe('请输入首条消息或添加附件。');
    expect(validateNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo',
      firstMessage: 'run tests',
    })).toBeNull();
    expect(validateNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo',
      firstMessage: '',
    }, { attachmentCount: 1 })).toBeNull();
  });

  it('summarizes the mobile create-session draft for the top overview strip', () => {
    expect(summarizeNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '',
      firstMessage: '',
    })).toMatchObject({
      agentLabel: 'Claude',
      canCreate: false,
      runtimeLabel: 'Claude · claude-sonnet-4-6 · medium',
      scopeLabel: '未选择项目路径',
      validationMessage: '请输入电脑端项目路径。',
      workspaceLabel: '项目',
    });

    expect(summarizeNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo/xdt-maker',
      firstMessage: 'run tests',
      extraDirs: ['/repo/docs', '/repo/docs', ''],
    })).toMatchObject({
      canCreate: true,
      scopeLabel: 'xdt-maker · +1 附加目录',
      validationMessage: null,
    });

    expect(summarizeNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo/xdt-maker',
      firstMessage: '',
    }, { attachmentCount: 2 })).toMatchObject({
      canCreate: true,
      validationMessage: null,
    });

    expect(summarizeNewSessionDraft({
      ...DRAFT_WITH_MODEL,
      agentKind: 'codex',
      workspaceKind: 'dialogue',
      workingDir: '',
      model: 'gpt-5.4',
      fastMode: true,
      firstMessage: 'review this',
    })).toMatchObject({
      agentLabel: 'Codex',
      canCreate: true,
      runtimeLabel: 'Codex · gpt-5.4 · medium · Fast',
      scopeLabel: '由电脑自动分配工作目录',
      workspaceLabel: '对话',
    });
  });

  it('builds a final mobile create preview before sending to the controlled computer', () => {
    expect(buildNewSessionCreatePreview({
      ...DRAFT_WITH_MODEL,
      workingDir: '',
      firstMessage: '',
    }, 'Carol Mac')).toMatchObject({
      title: '还不能创建',
      subtitle: '请输入电脑端项目路径。',
      details: [
        '设备:Carol Mac',
        '位置:未选择项目路径',
        '运行:Claude · claude-sonnet-4-6 · medium',
        '首条:未填写',
      ],
    });

    expect(buildNewSessionCreatePreview({
      ...DRAFT_WITH_MODEL,
      workspaceKind: 'dialogue',
      workingDir: '',
      firstMessage: '请帮我总结这个项目,并给出下一步建议。',
      model: 'claude-sonnet-4-6',
    }, 'Carol Mac')).toMatchObject({
      title: '准备创建并发送',
      subtitle: '确认后会在远程设备创建任务,并把首条消息加入队列。',
      details: [
        '设备:Carol Mac',
        '位置:对话工作区',
        '运行:Claude · claude-sonnet-4-6 · medium',
        '首条:请帮我总结这个项目,并给出下一步建议。',
      ],
    });

    expect(buildNewSessionCreatePreview({
      ...DRAFT_WITH_MODEL,
      workingDir: '/repo/xdt-maker',
      firstMessage: '',
    }, 'Carol Mac', { attachmentCount: 2 })).toMatchObject({
      title: '准备创建并发送',
      details: [
        '设备:Carol Mac',
        '位置:/repo/xdt-maker',
        '运行:Claude · claude-sonnet-4-6 · medium',
        '首条:仅发送附件',
        '附件:2 个',
      ],
    });
  });

  it('parses extra dirs text the same way create args expect arrays', () => {
    expect(parseExtraDirsInput(' /repo/docs\n/repo/tools, /repo/docs\n\n')).toEqual([
      '/repo/docs',
      '/repo/tools',
    ]);
  });

  it('serializes device candidates for new-session route params', () => {
    const encoded = serializeNewSessionDeviceOptions([
      { deviceId: ' pc ', name: ' PC ' },
      { deviceId: 'mac', name: '' },
      { deviceId: 'pc', name: 'Duplicate' },
    ]);

    expect(parseNewSessionDeviceOptions(encoded)).toEqual([
      { deviceId: 'pc', name: 'PC' },
      { deviceId: 'mac', name: '另一台电脑' },
    ]);
  });

  it('falls back to the route device when candidate params are missing or invalid', () => {
    expect(parseNewSessionDeviceOptions('', { deviceId: 'pc', name: 'PC' })).toEqual([
      { deviceId: 'pc', name: 'PC' },
    ]);
    expect(parseNewSessionDeviceOptions('not-json', { deviceId: 'pc', name: '' })).toEqual([
      { deviceId: 'pc', name: '另一台电脑' },
    ]);
    expect(parseNewSessionDeviceOptions('')).toEqual([]);
  });

  it('keeps the recent-project list nested-scrollable with a visible scroll indicator (#5013)', () => {
    const source = newSessionSources;
    // Scope the guard to this list: the remote directory FlatList already has
    // these props, so checking the whole page would miss the Android regression.
    // Native gesture dispatch still needs Android emulator/device verification.
    const lists = source.match(/<ScrollView\b[^>]*style=\{styles\.workspaceProjectList\}[^>]*>/g);
    expect(lists).toHaveLength(1);
    expect(lists![0]).toMatch(/\bnestedScrollEnabled(?:\s|=\{true\})/);
    expect(lists![0]).toMatch(/\bshowsVerticalScrollIndicator(?:\s|=\{true\})/);
    expect(lists![0]).toContain('keyboardShouldPersistTaps="handled"');
  });

  it('hosts the workspace popup outside scrolling and selector touch bounds (#5013)', () => {
    const source = ts.createSourceFile('new.tsx', readTextLf(
      resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8',
    ), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
    const panels: ts.JsxElement[] = [];
    const visit = (node: ts.Node) => {
      if (ts.isJsxElement(node) && node.openingElement.attributes.properties.some(
        (prop) => ts.isJsxAttribute(prop) && prop.name.getText(source) === 'testID'
          && prop.initializer && ts.isStringLiteral(prop.initializer)
          && prop.initializer.text === 'newSession.workspacePickerPanel',
      )) panels.push(node);
      ts.forEachChild(node, visit);
    };
    visit(source);
    expect(panels).toHaveLength(1);
    const ancestors: ts.JsxElement[] = [];
    for (let parent: ts.Node | undefined = panels[0].parent; parent; parent = parent.parent) {
      if (ts.isJsxElement(parent)) ancestors.push(parent);
    }
    expect(ancestors.map(node => node.openingElement.tagName.getText(source)))
      .not.toContain('ScrollView');
    expect(ancestors[0].openingElement.getText(source)).toContain('ref={workspacePickerHostRef}');
    expect(ancestors[0].getText(source)).not.toContain('testID="newSession.backButton"');
  });

  it('scrolls every workspace action together so fixed rows cannot consume a short viewport', () => {
    const source = ts.createSourceFile('new.tsx', readTextLf(
      resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8',
    ), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
    const actionIds = new Set([
      'newSession.workspaceDialogueOption',
      'newSession.workspaceProjectOption',
      'newSession.workspaceBrowseOption',
    ]);
    const scrollParents: ts.JsxElement[] = [];
    const visit = (node: ts.Node) => {
      if (ts.isJsxElement(node) && node.openingElement.attributes.properties.some(
        prop => ts.isJsxAttribute(prop) && prop.name.getText(source) === 'testID'
          && prop.initializer && ts.isStringLiteral(prop.initializer)
          && actionIds.has(prop.initializer.text),
      )) {
        for (let parent = node.parent; parent; parent = parent.parent) {
          if (ts.isJsxElement(parent) && parent.openingElement.tagName.getText(source) === 'ScrollView') {
            scrollParents.push(parent);
            break;
          }
        }
      }
      ts.forEachChild(node, visit);
    };
    visit(source);
    expect(scrollParents).toHaveLength(3);
    expect(new Set(scrollParents).size).toBe(1);
    expect(scrollParents[0].openingElement.getText(source)).toContain('styles.workspaceProjectList');
  });

  it('builds recent workspace quick picks from mirrored remote sessions', () => {
    const options = buildRecentWorkspaceOptions([
      remoteSession('old', {
        workingDir: '/repo/old',
        userSendAt: '2026-01-01T00:01:00.000Z',
        deviceLinkDeviceId: 'mac-a',
      }),
      remoteSession('latest-a', {
        workingDir: '/repo/app',
        userSendAt: '2026-01-01T00:05:00.000Z',
        deviceLinkDeviceId: 'mac-a',
      }),
      remoteSession('latest-b', {
        workingDir: '/repo/app',
        userSendAt: '2026-01-01T00:06:00.000Z',
        deviceLinkDeviceId: 'mac-a',
      }),
      remoteSession('dialogue', {
        workspaceKind: 'dialogue',
        workingDir: null,
        deviceLinkDeviceId: 'mac-a',
      }),
      remoteSession('other-device', {
        workingDir: '/repo/other',
        userSendAt: '2026-01-01T00:10:00.000Z',
        deviceLinkDeviceId: 'mac-b',
      }),
      remoteSession('deleted', {
        workingDir: '/repo/deleted',
        status: 'deleted',
        deviceLinkDeviceId: 'mac-a',
      }),
    ], 'mac-a');

    expect(options).toEqual([
      {
        workingDir: '/repo/app',
        title: 'app',
        sessionCount: 2,
        lastActivityAt: '2026-01-01T00:06:00.000Z',
      },
      {
        workingDir: '/repo/old',
        title: 'old',
        sessionCount: 1,
        lastActivityAt: '2026-01-01T00:01:00.000Z',
      },
    ]);
  });

  // #6916, unit: the production picker must display host metadata without changing its path.
  it('uses the selected host alias for recent workspace quick picks', () => {
    const sessions = [remoteSession('app', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a' })];
    const aliases = new Map([
      ['device:mac-a:/repo/app', 'Customer Portal'],
      ['device:mac-b:/repo/app', 'Other Portal'],
    ]);
    expect(buildRecentWorkspaceOptions(sessions, 'mac-a', 6, aliases)[0]).toMatchObject({
      title: 'Customer Portal', workingDir: '/repo/app',
    });
    expect(buildRecentWorkspaceOptions(sessions, 'mac-a', 6, new Map())[0].title).toBe('app');
  });

  it('keeps mixed local/SSH recent-workspace names independent of row order', () => {
    const aliases = new Map([['device:mac-a:/repo/app', 'Local name']]);
    const local = remoteSession('local', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a' });
    const ssh = remoteSession('ssh', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a', remoteHostId: 'ssh-a' });
    for (const rows of [[local, ssh], [ssh, local]]) {
      expect(buildRecentWorkspaceOptions(rows, 'mac-a', 6, aliases)[0]).toMatchObject({ title: 'app', sessionCount: 2 });
    }
    expect(buildRecentWorkspaceOptions([ssh], 'mac-a', 6, aliases)[0].title).toBe('app');
  });

  // Remote path strings deliberately model the host OS, not the test runner's filesystem.
  it.each([
    ['slash direction', 'D:\\projects\\cindy', 'D:/projects/cindy'],
    ['letter case', 'D:/projects/cindy', 'd:/PROJECTS/Cindy'],
    ['trailing separator', 'D:\\projects\\cindy', 'D:\\projects\\cindy\\'],
    ['combined variants', 'D:\\projects\\cindy', 'd:/PROJECTS/cindy/'],
    ['drive root', 'D:\\', 'd:/'],
    ['UNC share', '\\\\Server\\Share\\cindy', '//server/share/CINDY/'],
    ['worktree', 'D:\\projects\\cindy', 'd:/PROJECTS/cindy/.cindy-worktrees/branch'],
  ])('deduplicates equivalent remote Windows %s before sorting and limiting', (_name, original, variant) => {
    const options = buildRecentWorkspaceOptions([
      remoteSession('original', { workingDir: original, deviceLinkDeviceId: 'pc' }),
      remoteSession('variant', {
        workingDir: variant, deviceLinkDeviceId: 'pc', userSendAt: '2026-01-01T00:06:00.000Z',
      }),
      remoteSession('other', {
        workingDir: 'D:/projects/other', deviceLinkDeviceId: 'pc', userSendAt: '2026-01-01T00:05:00.000Z',
      }),
      remoteSession('another-host', {
        workingDir: variant, deviceLinkDeviceId: 'another-pc', userSendAt: '2026-01-01T00:07:00.000Z',
      }),
    ], 'pc', 2);

    expect(options).toHaveLength(2);
    expect(options[0]).toMatchObject({
      workingDir: original, sessionCount: 2, lastActivityAt: '2026-01-01T00:06:00.000Z',
    });
    expect(options[1]).toMatchObject({ workingDir: 'D:/projects/other', sessionCount: 1 });
  });

  it('preserves remote POSIX case and literal backslashes while ignoring trailing slashes', () => {
    const paths = ['/repo/App', '/repo/app', '/repo/app/', '/repo/weird\\name', '/repo/weird/name'];
    const options = buildRecentWorkspaceOptions(paths.map((workingDir, index) =>
      remoteSession(String(index), { workingDir }),
    ));
    expect(options).toHaveLength(4);
    expect(options.find((option) => option.workingDir === '/repo/app')?.sessionCount).toBe(2);
    expect(options.map((option) => option.workingDir)).toEqual(expect.arrayContaining([
      '/repo/App', '/repo/weird\\name', '/repo/weird/name',
    ]));
  });

  it('excludes worker-only directories before limiting recent workspace picks', () => {
    const sessions = [
      ...Array.from({ length: 6 }, (_, index) => remoteSession(`worker-${index}`, {
        orcaRole: 'worker',
        workingDir: `/scratch/worker-${index}`,
        userSendAt: '2026-01-01T00:10:00.000Z',
      })),
      remoteSession('lead', {
        orcaRole: 'lead',
        workingDir: '/repo/lead',
        userSendAt: '2026-01-01T00:05:00.000Z',
      }),
      remoteSession('ordinary', { workingDir: '/repo/ordinary' }),
    ];

    const options = buildRecentWorkspaceOptions(sessions);
    expect(options.map((option) => option.workingDir)).toEqual(['/repo/lead', '/repo/ordinary']);
    expect(pickInitialNewSessionWorkspace('', options)).toBe('/repo/lead');
    expect(buildRecentWorkspaceOptions(sessions.slice(0, 6))).toEqual([]);
  });

  it('does not let workers change a user project count, activity, or ordering', () => {
    const userSessions = [
      remoteSession('older', {
        workingDir: '/repo/shared',
        userSendAt: '2026-01-01T00:01:00.000Z',
      }),
      remoteSession('newer', {
        workingDir: '/repo/newer',
        userSendAt: '2026-01-01T00:05:00.000Z',
      }),
    ];
    const workers = ['/repo/shared', '/repo/shared/.cindy-worktrees/worker'].map((workingDir, index) =>
      remoteSession(`worker-${index}`, {
        orcaRole: 'worker',
        workingDir,
        userSendAt: '2026-01-01T00:10:00.000Z',
      }),
    );

    expect(buildRecentWorkspaceOptions([...workers, ...userSessions])).toEqual(
      buildRecentWorkspaceOptions(userSessions),
    );
  });

  it('folds managed worktree sessions into their base repo project', () => {
    const options = buildRecentWorkspaceOptions([
      remoteSession('base', {
        workingDir: '/repo/app',
        userSendAt: '2026-01-01T00:01:00.000Z',
      }),
      remoteSession('current-worktree', {
        workingDir: '/repo/app/.cindy-worktrees/auto-one',
        worktreePath: '/repo/app/.cindy-worktrees/auto-one',
        userSendAt: '2026-01-01T00:03:00.000Z',
      }),
      remoteSession('legacy-worktree', {
        workingDir: '/repo/app/.xdt-worktrees/auto-two',
        worktreePath: '/repo/app/.xdt-worktrees/auto-two',
        userSendAt: '2026-01-01T00:02:00.000Z',
      }),
    ]);

    expect(options).toEqual([{
      workingDir: '/repo/app',
      title: 'app',
      sessionCount: 3,
      lastActivityAt: '2026-01-01T00:03:00.000Z',
    }]);
    expect(pickInitialNewSessionWorkspace('', options)).toBe('/repo/app');
  });

  it('prefills a blank new session from the most recent workspace only', () => {
    const recentWorkspaces = buildRecentWorkspaceOptions([
      remoteSession('old', {
        workingDir: '/repo/old',
        userSendAt: '2026-01-01T00:01:00.000Z',
      }),
      remoteSession('latest', {
        workingDir: '/repo/latest',
        userSendAt: '2026-01-01T00:10:00.000Z',
      }),
    ]);

    expect(pickInitialNewSessionWorkspace('', recentWorkspaces)).toBe('/repo/latest');
    expect(pickInitialNewSessionWorkspace(' /repo/from-route ', recentWorkspaces)).toBeNull();
    expect(pickInitialNewSessionWorkspace('', [])).toBeNull();
  });

  it('prefers the directory the user last explicitly chose on this device over the most recent workspace (#4103)', () => {
    const recentWorkspaces = buildRecentWorkspaceOptions([
      remoteSession('latest', { workingDir: '/repo/latest', userSendAt: '2026-01-01T00:10:00.000Z' }),
      remoteSession('third', { workingDir: '/repo/third', userSendAt: '2026-01-01T00:01:00.000Z' }),
    ]);
    // 记忆的目录优先;不要求它仍在最近列表里(列表只保留 6 项,用户本就可从浏览器选任意目录)
    expect(pickInitialNewSessionWorkspace('', recentWorkspaces, '/repo/third')).toBe('/repo/third');
    // 路径原样返回:首尾空格可能是目录名的一部分(review:Greptile P1)
    expect(pickInitialNewSessionWorkspace('', recentWorkspaces, ' /elsewhere/app ')).toBe(' /elsewhere/app ');
    expect(pickInitialNewSessionWorkspace('', [], '/repo/third')).toBe('/repo/third');
    // 草稿已有目录时仍然不动;没有记忆时回落最近项目首项
    expect(pickInitialNewSessionWorkspace('/explicit', recentWorkspaces, '/repo/third')).toBeNull();
    expect(pickInitialNewSessionWorkspace('', recentWorkspaces, null)).toBe('/repo/latest');
    expect(pickInitialNewSessionWorkspace('', recentWorkspaces, '   ')).toBe('/repo/latest');
  });

  it('normalizes create results and can synthesize a fallback session row', () => {
    const result = normalizeCreateSessionResult({
      sessionId: 's-new',
      agentKind: 'claude-code',
      workDir: '/repo',
      usedProjectContext: true,
    });
    expect(result).toMatchObject({ sessionId: 's-new', workDir: '/repo' });

    expect(sessionFromCreateResult(result!, {
      agentKind: 'claude-code',
      workspaceKind: 'project',
      workingDir: '/repo',
      model: 'claude-sonnet-4-6',
      effort: 'medium',
      permissionMode: 'acceptEdits',
      fastMode: false,
      providerId: null,
      firstMessage: '帮我排查登录失败',
    }, new Date('2026-06-16T10:00:00.000Z'))).toMatchObject({
      id: 's-new',
      title: '帮我排查登录失败',
      workingDir: '/repo',
      workspaceKind: 'project',
      agentKind: 'cc',
      userSendAt: '2026-06-16T10:00:00.000Z',
    });

    expect(sessionFromCreateResult({
      sessionId: 's-dialogue',
      agentKind: 'codex',
      workDir: '/userData/dialogues/2026-06-16/s-dialogue',
    }, {
      agentKind: 'codex',
      workspaceKind: 'dialogue',
      workingDir: '',
      model: 'gpt-5.4',
      effort: 'medium',
      permissionMode: 'acceptEdits',
      fastMode: true,
      providerId: null,
    }, new Date('2026-06-16T10:00:00.000Z'))).toMatchObject({
      id: 's-dialogue',
      workingDir: '/userData/dialogues/2026-06-16/s-dialogue',
      workspaceKind: 'dialogue',
      agentKind: 'codex',
    });

    expect(normalizeCreateSessionResult({ sessionId: '' })).toBeNull();
    expect(normalizeCreateSessionResult(null)).toBeNull();
  });

  it('sessionFromCreateResult carries the draft providerId into the synthesized session (codex P1)', () => {
    const session = sessionFromCreateResult({ sessionId: 's-p' }, {
      agentKind: 'claude-code',
      workspaceKind: 'dialogue',
      workingDir: '',
      model: 'deepseek-v4-flash',
      effort: 'medium',
      permissionMode: 'acceptEdits',
      fastMode: false,
      providerId: 'deepseek',
    });
    expect(session.providerId).toBe('deepseek');
    expect(session.title).toBe('New Maker');
    // 未绑定来源的草稿 → null(默认路由),与真实会话同形
    expect(sessionFromCreateResult({ sessionId: 's-n' }, {
      agentKind: 'claude-code',
      workspaceKind: 'dialogue',
      workingDir: '',
      model: 'claude-sonnet-4-6',
      effort: '',
      permissionMode: 'acceptEdits',
      fastMode: false,
      providerId: null,
    }).providerId).toBeNull();
  });
});

describe('new session composer surface', () => {
  // 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);
    const slashSource = newSource.slice(slashStart, slashEnd);
    const atStart = slashEnd;
    const atEnd = newSource.indexOf('const removeAttachment = useCallback', atStart);
    const atSource = newSource.slice(atStart, atEnd);

    for (const source of [slashSource, atSource]) {
      expect(source).toContain('const current = firstMessageRef.current;');
      expect(source).toContain('const selection = { start: next.length, end: next.length };');
      expect(source.indexOf('setFirstMessageDraft(next)')).toBeLessThan(
        source.indexOf('setFirstMessageSelection(selection)'),
      );
    }
  });

  it('does not double-apply the Android safe-area inset to the top navigation', () => {
    const newSource = newSessionSources;

    expect(newSource).toContain(
      "const NEW_SESSION_SCREEN_TOP_PADDING = Platform.OS === 'android' ? 0 : spacing.xl;",
    );
    expect(newSource).toContain('paddingTop: NEW_SESSION_SCREEN_TOP_PADDING,');
  });

  it('uses the shared platform keyboard avoidance rule for the new-session composer', () => {
    const newSource = newSessionSources;
    const normalizedNewSource = newSource.replace(/\r\n/g, '\n');

    expect(newSource).toContain("import { keyboardAvoidingBehaviorForPlatform } from '@/session/mobileNativeShellLayout';");
    expect(normalizedNewSource).toContain(`behavior={keyboardAvoidingBehaviorForPlatform(
          Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'web',
        )}`);
    expect(newSource).not.toContain("Platform.OS === 'ios' ? 'padding' : undefined");
  });

  // 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;');
  });
});

describe('new session worktree wiring (source locks)', () => {
  // worktree 两步建会话的接线不变量(纯函数测试覆盖不到的部分):
  //  - worktree:create 必须发生在 startNewSessionCreation 之前(远程没有改已建会话
  //    workingDir 的通道,且 create 对同 sessionId 重跑不幂等,不得进乐观管线重试面);
  //  - 两步共用同一预生成 sessionId(工作端 close-session 按绑定回收 worktree);
  //  - 成功后以 meta.path 替换 effectiveDraft.workingDir 再进管线;
  //  - 失败(业务 {ok:false} / invoke 抛错)早退留在表单,不建会话。
  const newSource = newSessionSources;

  // 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', () => {
    expect(newSource).toContain(
      "if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return undefined;",
    );
    const detectEffect = newSource.indexOf(
      'return maker.worktree.detectCwd(cwd);',
    );
    const preferenceEffect = newSource.indexOf(
      'const worktreeSeedAgentKindRef',
      detectEffect,
    );
    const detectBlock = newSource.slice(detectEffect, preferenceEffect);
    expect(detectBlock).toContain('connectionEpoch,');
    expect(detectBlock).toContain('deviceLinkStatus,');
    expect(detectBlock).toContain('presenceVersion,');
  });

  it('settles an unowned cleanup obligation before creating another worktree', () => {
    const recovery = newSource.indexOf(
      'const recovery = await recoverPendingPrecreatedWorktrees(worktreeAccountId, {',
    );
    const pendingGuard = newSource.indexOf(
      '!recovery.storageReadable',
      recovery,
    );
    const sessionId = newSource.indexOf(
      'const sessionId = recoveryIdentity?.sessionId ?? createNewSessionId();',
      pendingGuard,
    );
    const worktreeCreate = newSource.indexOf(
      'await maker.worktree.create(createRequest)',
      sessionId,
    );

    expect(recovery).toBeGreaterThan(-1);
    expect(pendingGuard).toBeGreaterThan(recovery);
    expect(sessionId).toBeGreaterThan(pendingGuard);
    expect(worktreeCreate).toBeGreaterThan(sessionId);
    expect(newSource.slice(recovery, pendingGuard)).toContain(
      'record.deviceId !== selectedDeviceId',
    );
    expect(newSource.slice(pendingGuard, sessionId)).toContain(
      'recovery.retained > 0',
    );
    expect(newSource.slice(pendingGuard, sessionId)).toContain(
      "setError(t('session.new.worktreeCleanupPending'))",
    );
  });

  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('captureNewSessionOwner(', ownerCapture);
    const recovery = newSource.indexOf(
      'const recovery = await recoverPendingPrecreatedWorktrees(worktreeAccountId, {',
      ownerCheck,
    );
    const recoveryFence = newSource.indexOf('isCurrent: isCurrentOwner,', recovery);
    const pipeline = newSource.indexOf('startNewSessionCreation({', recoveryFence);
    const pipelineFence = newSource.indexOf('isCurrentOwner,', pipeline);

    expect(ownerCapture).toBeGreaterThan(-1);
    expect(ownerCheck).toBeGreaterThan(ownerCapture);
    expect(recovery).toBeGreaterThan(ownerCheck);
    expect(recoveryFence).toBeGreaterThan(recovery);
    expect(pipeline).toBeGreaterThan(recoveryFence);
    expect(pipelineFence).toBeGreaterThan(pipeline);
  });

  it('persists a recoveryKey reservation before allowing remote worktree creation', () => {
    const hold = newSource.indexOf(
      'releasePrecreatedRegistration = holdPrecreatedWorktreeRegistration(sessionId);',
    );
    const reservation = newSource.indexOf(
      'const reservationRecorded = await registerPendingPrecreatedWorktree(',
      hold,
    );
    const failedPersistence = newSource.indexOf(
      'if (!reservationRecorded)',
      reservation,
    );
    const remoteCreate = newSource.indexOf(
      'await maker.worktree.create(createRequest)',
      failedPersistence,
    );

    expect(hold).toBeGreaterThan(-1);
    expect(reservation).toBeGreaterThan(hold);
    expect(failedPersistence).toBeGreaterThan(reservation);
    expect(remoteCreate).toBeGreaterThan(failedPersistence);
    expect(newSource.slice(failedPersistence, remoteCreate)).toContain(
      "setGoalError(t('session.new.worktreeRecoveryStateFailed'))",
    );
    expect(newSource.slice(remoteCreate, remoteCreate + 500)).toContain(
      'recoveryKey,',
    );
    expect(newSource.slice(remoteCreate, remoteCreate + 1_500)).not.toContain(
      'maker.worktree.discardPrecreated',
    );
    expect(newSource.slice(remoteCreate, remoteCreate + 2_500)).toContain(
      "setGoalError(t('session.new.worktreeCleanupPending'))",
    );
  });

  it('binds eligibility and source branch to device/cwd, then carries cleanup metadata into the pipeline', () => {
    expect(newSource).toContain('const worktreeTarget = {');
    expect(newSource).toContain('deviceId: selectedDeviceId ??');
    expect(newSource).toContain('worktreeEligibilityForTarget(worktreeProbe, worktreeTarget)');
    expect(newSource).toContain('probeGeneration: `${connectionEpoch}\\u0000${presenceVersion}`');
    expect(newSource).toContain('worktreeSourceBranchFromPreference(');
    expect(newSource).toContain('shouldAcceptWorktreeBranchListResult({');
    expect(newSource).toContain('sourceBranch: worktreeIntent.sourceBranch,');
    expect(newSource).toContain('const worktreeIntent = prepareWorktreeCreateIntent(');
    expect(newSource).toContain('isWorktreeCreateIntentCurrent(worktreeIntent)');
    expect(newSource).toContain('precreatedWorktree = {');
    expect(newSource).toContain('recoveryKey,');
    expect(newSource).toContain('originalWorkingDir: effectiveDraft.workingDir,');
    expect(newSource).toContain('precreatedWorktree,');
  });

  it('keeps branch selection independent from the worktree checkbox', () => {
    const disabledStart = newSource.indexOf('const worktreeBranchDisabled =');
    const disabledEnd = newSource.indexOf(';', disabledStart);
    expect(disabledStart).toBeGreaterThan(-1);
    expect(newSource.slice(disabledStart, disabledEnd + 1)).not.toContain('worktreeEnabled');

    const selectStart = newSource.indexOf('const selectWorktreeSourceBranch = useCallback(');
    const selectEnd = newSource.indexOf('\n  }, [', selectStart);
    const selectBlock = newSource.slice(selectStart, selectEnd);
    expect(selectBlock).toContain('maker.applyNewMakerWorktreeBranchPref(');
    expect(selectBlock).not.toContain('toggleWorktree');
    expect(selectBlock).not.toContain('maker.applyNewMakerWorktreePref(');
    expect(newSource).toContain('maker.getNewMakerWorktreeBranchPref(baseRepo)');
    expect(newSource).toContain('useRemoteNewMakerWorktreeBranchPreference(');
    expect(newSource).toContain('testID="newSession.worktreeBranchPicker"');
    expect(newSource).toContain('testID="newSession.worktreeToggle"');
    expect(newSource).toContain("t('session.new.worktreeShortLabel')");
    expect(newSource).not.toContain('>worktree</Text>');
  });

  it('keeps Goal on the same worktree contract as ordinary creation', () => {
    const goalStart = newSource.indexOf('const createGoalSession = useCallback(');
    const goalEnd = newSource.indexOf('\n\n  return (', goalStart);
    const goalBody = newSource.slice(goalStart, goalEnd);
    const gate = goalBody.indexOf('if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {');
    const worktreeCreate = goalBody.indexOf(
      'await maker.worktree.create(createRequest)',
    );
    const sessionCreate = goalBody.indexOf('maker.createSession(createOpts)');

    expect(goalStart).toBeGreaterThan(-1);
    expect(gate).toBeGreaterThan(-1);
    expect(worktreeCreate).toBeGreaterThan(gate);
    expect(sessionCreate).toBeGreaterThan(worktreeCreate);
    expect(goalBody).toContain('id: sessionId,');
    expect(goalBody).toContain('effectiveDraft = { ...effectiveDraft, workingDir: response.meta.path };');
    expect(goalBody).toContain('sessionId: precreatedWorktree!.sessionId');
    expect(goalBody).toContain('sessionId: precreatedWorktree.sessionId');
  });

  it('keeps branch preference GET fail-closed except for explicit old-channel compatibility', () => {
    const pullStart = newSource.indexOf('const seq = ++worktreeBranchPreferencePullSeqRef.current;');
    const pullEnd = newSource.indexOf('\n  }, [', pullStart);
    const pullBody = newSource.slice(pullStart, pullEnd);
    expect(pullBody).toContain('if (isWorktreeChannelNotAllowedError(err))');
    expect(pullBody).not.toContain('setWorktreeBranchPreferenceReadyKey(syncKey);\n      });');
    expect(pullBody).toContain('const newerPush = remoteSessionStore.getNewMakerWorktreeBranchPreference(');
    expect(pullBody).toContain('worktreeBranchPreferenceReadyKeyRef.current = null;');
    expect(pullBody).toContain('isValidWorktreeBranchPreferenceSnapshot(snapshot, baseRepo)');
  });

  it('propagates recovery ownership probe failures instead of treating them as unclaimed', () => {
    const recoveryCalls = newSource.match(/isExactRemoteSessionClaimed\(/g) ?? [];
    expect(recoveryCalls).toHaveLength(3); // ordinary + Goal recovery + Goal compensation
    expect(newSource).not.toContain('return false;\n            }\n          },\n          shouldDefer:');
  });

  it('applies the protocol timeout override map to mobile invokes (worktree:create needs 60s)', async () => {
    // 2026-07-29 与 main 合并后,移动端逐通道超时统一走 invokeTimeouts 的
    // resolveMobileInvokeTimeoutMs(mobile 专属表 → 协议契约表 INVOKE_TIMEOUT_OVERRIDES_MS
    // 兜底),worktree:create 的 60s 预算经协议表兜底生效——两层缺一都会让
    // 被控端建完 worktree 而控制端已超时放弃。
    const contextSource = readTextLf(
      resolve(process.cwd(), 'src/device-link/DeviceLinkContext.tsx'),
      'utf8',
    );
    expect(contextSource).toContain('resolveMobileInvokeTimeoutMs(channel, args)');
    const { resolveMobileInvokeTimeoutMs } = await import('@/device-link/invokeTimeouts');
    expect(resolveMobileInvokeTimeoutMs('worktree:create')).toBe(60_000);
  });
});

describe('submit guard catalog wiring (source locks)', () => {
  // 提交终检目录取信的接线不变量(纯函数测试覆盖不到的 new.tsx 接线):
  //  - 两处守卫(create / createGoalSession)都必须走 resolveSubmitGuardCatalog
  //    (代际安全:唯一数据源 = 设备缓存 + 代际,不再读渲染期 rows——catalogReadyRef
  //    是渲染镜像,驱逐窗口内不可信,独立 review P1-1);
  //  - 守卫内 buildRows 重建必须带 selectedModelId/selectedProviderId —— 缺了就没有
  //    keepSelected 豁免,被被控端隐藏 override 的选中行会被过滤出终检 rows,
  //    手动选中的模型被静默联合回退(独立 review P2);
  //  - 两处守卫都必须全程设备守卫(切设备放弃创建,Greptile P1 跨设备混用):
  //    deviceAtCreate 捕获 + ensureDeviceAlive/abortIfDeviceSwitched,handoff
  //    (startNewSessionCreation / maker.createSession / goal.set)前必复核;
  //    已 precreate 后失配必须走 ledger 补偿(forgetPendingPrecreatedWorktree)。
  const newSource = newSessionSources;

  it('both submit guards resolve catalog trust via the generation-safe helper', () => {
    const guardCalls = newSource.match(/resolveSubmitGuardCatalog\(\{/g) ?? [];
    expect(guardCalls.length).toBe(2);
    // 守卫不再消费渲染期 rows / catalogReadyRef
    const staleReady = newSource.match(/resolveGuardCatalog\(\s*catalogReadyRef\.current,/g) ?? [];
    expect(staleReady.length).toBe(0);
    expect(newSource).toContain('getCachedDeviceProviders(guardDeviceId)');
    expect(newSource).toContain('getDeviceProvidersGen(guardDeviceId)');
  });

  it('every catalog rebuild in the guards passes the keepSelected exemption pair', () => {
    // 两处守卫内的 buildRows(2 处)带 effectiveDraft 豁免对 + 渲染期(1 处)带 draft
    // + 轮次 35 create 管线 revalidate(1 处)带 effectiveDraft 豁免对 = 4 处
    // (轮次 36 删除了 Goal 路径的旧 authResult fresh 校验——时间序错误,guard
    // 已用 fetchDeviceProvidersFresh 强制刷新,不再二次校验)。
    const selectedModel = newSource.match(/selectedModelId: (effectiveDraft|draft|selected)\.model,/g) ?? [];
    const selectedProvider = newSource.match(/selectedProviderId: (effectiveDraft|draft|selected)\.providerId,/g) ?? [];
    expect(selectedModel.length).toBe(4);
    expect(selectedProvider.length).toBe(4);
  });

  it('both guards are device-guarded through to the handoff, with ACK-gated ledger compensation after precreate', () => {
    // 设备快照取自闭包 selectedDeviceId(独立 review P1-1)+ 入口立即与 ref 核对
    expect(newSource.match(/const deviceAtCreate = selectedDeviceId;/g) ?? []).toHaveLength(2);
    expect(newSource.match(/if \(selectedDeviceRef\.current !== deviceAtCreate\) return;/g) ?? []).toHaveLength(2);
    expect(newSource.match(/const ensureDeviceAlive = \(\): boolean =>/g) ?? []).toHaveLength(2);
    expect(newSource.match(/const abortIfDeviceSwitched = async/g) ?? []).toHaveLength(2);
    expect(newSource.match(/compensatePrecreatedWorktree\(\{/g) ?? []).toHaveLength(2);
    expect(newSource.match(/parseAck: parseDiscardPrecreatedAck,/g) ?? []).toHaveLength(2);
    // 真局部 slice(独立 review round-22 Standards P1:全文件 indexOf 命中 create 首个
    // 检查,Goal 检查删掉也照样绿)
    const createStart = newSource.indexOf('const createMessageSession = useCallback');
    const goalStart = newSource.indexOf('const createGoalSession = useCallback');
    expect(createStart).toBeGreaterThan(-1);
    expect(goalStart).toBeGreaterThan(createStart);
    const createSlice = newSource.slice(createStart, goalStart);
    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 假通过)。
    const goalEntryCheck = goalSlice.indexOf('if (selectedDeviceRef.current !== deviceAtCreate) return;');
    const goalSetBusy = goalSlice.indexOf('setGoalBusy(true)');
    expect(goalEntryCheck).toBeGreaterThan(-1);
    expect(goalSetBusy).toBeGreaterThan(-1);
    expect(goalEntryCheck).toBeLessThan(goalSetBusy);
    // 有界稳定循环:两段各含「每轮 runGuard 后同步核对 genAt」+ 耗尽降 unknown/fail-open
    expect(createSlice.match(/if \(getDeviceProvidersGen\(guardDeviceId\) === guardResult\.genAt\) break;/g) ?? []).toHaveLength(1);
    // goal:prepare 循环(1)+ post-started 循环(前查 + 后查,2)+ 鉴权降级 re-fence(1)
    //   + 设备切换 commit 分支 re-fence(1)
    expect(goalSlice.match(/if \(getDeviceProvidersGen\(guardDeviceId\) === guardResult\.genAt\) break;/g) ?? []).toHaveLength(5);
    const failOpen = 'rows: [], providers: [], catalogKnown: false, genAt: getDeviceProvidersGen(guardDeviceId),';
    const failOpenCount = (slice: string): number =>
      slice.split(failOpen).length - 1;
    expect(failOpenCount(createSlice)).toBe(2); // 哨兵 + 耗尽
    expect(failOpenCount(goalSlice)).toBe(5); // 哨兵 + prepare 耗尽 + started 后耗尽 + 鉴权降级 re-fence + 设备切换 re-fence
    // create:apply 后零 await 直至 handoff(同一 turn)。Standards P1:endpoint 必须
    // 在 apply 之后(endpoint 前移会让空 slice 假通过零 await)。
    const createApply = createSlice.indexOf('applyGuard(guardResult);');
    const createHandoff = createSlice.indexOf('startNewSessionCreation({');
    expect(createApply).toBeGreaterThan(-1);
    expect(createHandoff).toBeGreaterThan(createApply);
    const createBetween = createSlice
      .slice(createApply, createHandoff)
      .replace(/\/\/[^\n]*/g, '');
    expect(createBetween).not.toMatch(/await /);
    // goal:最后核对后零 await 至 createSession(apply 前的 downgrade 分支是切换时早退,不在此段)
    const goalApply = goalSlice.indexOf('applyGuard(guardResult);');
    const goalCreate = goalSlice.indexOf('const created = await maker.createSession');
    expect(goalApply).toBeGreaterThan(-1);
    expect(goalCreate).toBeGreaterThan(goalApply);
    const goalBetween = goalSlice
      .slice(goalApply, goalCreate)
      .replace(/\/\/[^\n]*/g, '');
    expect(goalBetween).not.toMatch(/await /);
    // 轮次 42 终检复核(独立审核者 P1):apply 前的设备复核必须是**同步快路径**——
    // 先 ensureDeviceAlive 同步判,未切换零 await 直达 handoff(维持零 await 不变量);
    // await abortIfDeviceSwitched 只允许出现在已切换的早退分支里。裸
    // `if (await abortIfDeviceSwitched())` 会让出微任务,ref 更新排队时打开竞态。
    // 注意 prepare 段(guard 循环前)的裸 await 复核是合法的「可取消 await」,
    // 断言只覆盖 guard 循环后到 apply 的 commit 前区段。
    const finalCheckMarker = '// 终检刷新(await 网络往返)期间设备可能已切换';
    const finalCheckStart = goalSlice.indexOf(finalCheckMarker);
    expect(finalCheckStart).toBeGreaterThan(-1);
    const goalFinalCheck = goalSlice.slice(finalCheckStart, goalApply);
    expect(goalFinalCheck).toContain('if (!ensureDeviceAlive()) {');
    expect(goalFinalCheck).not.toMatch(/if \(await abortIfDeviceSwitched\(\)\)/);
  });

  it('goal failure restore payload is single-use: cleared after goal.set success (independent reviewer P2)', () => {
    // 失败接回的 objective/limits 载荷(codex review P2)必须一次性消费:goal.set
    // 成功后清 goalRestore state 与路由参数(goalObjective/goalLimits/goalError),
    // 否则清掉该 Goal 重新挂载表单仍带旧输入、页面重挂载再次恢复旧值。
    const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
    expect(sessionSource).toContain("from '@/session/goalLimitsRouteParam'");
    expect(sessionSource).toContain('parseGoalLimitsRouteParam(readRouteParam(params.goalLimits))');
    expect(sessionSource).toContain('setGoalRestore(null);');
    // 换代清理 effect 也含 setGoalRestore(null)(codex P2)——「一次性消费」锚定
    // handleSetGoal 成功路径的最后一处(lastIndexOf),不用首次命中。
    const setParamsBlock = sessionSource.slice(
      sessionSource.lastIndexOf('setGoalRestore(null);'),
      sessionSource.lastIndexOf('setGoalRestore(null);') + 400,
    );
    expect(setParamsBlock).toContain('goalObjective: undefined');
    expect(setParamsBlock).toContain('goalLimits: undefined');
    expect(setParamsBlock).toContain('goalError: undefined');
    // 一次性消费必须发生在 goal.set 成功之后(与表单关闭同一段),不是任意位置
    const goalSetSuccess = sessionSource.indexOf('await maker.goal.set({ sessionId, ...input });');
    const restoreClear = sessionSource.lastIndexOf('setGoalRestore(null);');
    expect(goalSetSuccess).toBeGreaterThan(-1);
    expect(restoreClear).toBeGreaterThan(goalSetSuccess);
    // initial 优先级:恢复载荷优先于 composer 文字带入;无载荷时 initialObjective
    // 仍从 composer 带入(旧行为)。渲染前按 sessionId 过滤(codex review P1):
    // 恢复值带 sessionId 归属,非当前任务立即失效,新表单不用旧目标初始化。
    expect(sessionSource).toContain('goalRestore && goalRestore.sessionId === sessionId ? goalRestore : undefined');
    const viewCall = sessionSource.slice(
      sessionSource.indexOf('initial={goalRestoreForSession}') - 200,
      sessionSource.indexOf('initial={goalRestoreForSession}') + 300,
    );
    expect(viewCall).toContain('initial={goalRestoreForSession}');
    expect(viewCall).toContain('initialObjective={goalRestoreForSession ? undefined : (draftRef.current.trim() || undefined)}');
  });

  it('goal 接回载荷按 sessionId 换代清理:切任务不残留旧 objective/limits(codex P2)', () => {
    // 任务抽屉 replaceParams 原地更新同一 SessionScreen 实例,goalRestore/goalError
    // 只在首次挂载初始化——sessionId 变化必须清理,否则新任务 Goal 表单预填旧目标、
    // 甚至把旧目标提交到新任务(codex review P2)。
    const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
    // 换代清理 effect 存在:prevSessionIdRef 记录上次 sessionId,变化时清 goalRestore + goalError
    const cleanEffect = sessionSource.indexOf('prevSessionIdRef.current !== sessionId');
    expect(cleanEffect).toBeGreaterThan(-1);
    const effectBlock = sessionSource.slice(cleanEffect - 200, cleanEffect + 400);
    expect(effectBlock).toContain('setGoalRestore(null);');
    expect(effectBlock).toContain('setGoalError(null);');
    expect(effectBlock).toContain('prevSessionIdRef.current = sessionId;');
    // ref 与当前 sessionId 同步初始化(useRef(sessionId)):首次挂载 prev===cur 不触发
    // 清理,保留路由带入的接回值(与「一次性消费」语义兼容)
    const refInit = sessionSource.indexOf('useRef(sessionId)');
    expect(refInit).toBeGreaterThan(-1);
    expect(refInit).toBeLessThan(cleanEffect);
    // 清理 effect 依赖 sessionId;位于 goalRestore 定义之后(初始化完成才可能清)
    const restoreInit = sessionSource.indexOf('const [goalRestore, setGoalRestore]');
    expect(restoreInit).toBeGreaterThan(-1);
    expect(cleanEffect).toBeGreaterThan(restoreInit);
    // 一次性消费不依赖本 effect:handleSetGoal 成功路径仍显式清 goalRestore(防误删
    // 同任务内的路由清参语义)
    expect(sessionSource).toContain('setGoalRestore(null);');
  });

  it('goal 表单按 sessionId 重挂载:子表单内部 state 随任务换代重置(codex P2)', () => {
    // 第 58 轮只清理父层 goalRestore;ContextSheetGoalCreateForm 的
    // objective/limits/limitsTouched 只在挂载时 useState(initial) 初始化一次,
    // 同实例下不随 initial 清空——旧目标仍显示并可提交到新任务。key={sessionId}
    // 强制表单组件在任务换代时重挂载,内部字段从新 initial 重新初始化。
    const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
    const viewCall = sessionSource.indexOf('<ContextSheetGoalView');
    expect(viewCall).toBeGreaterThan(-1);
    const callBlock = sessionSource.slice(viewCall, viewCall + 120);
    expect(callBlock).toContain('key={sessionId}');
    // 表单内部确实只在挂载时读 initial(useState 初始化)——重挂载是唯一同步手段
    const viewSource = readTextLf(resolve(process.cwd(), 'src/session/ContextSheetGoalView.tsx'), 'utf8');
    expect(viewSource).toContain('useState(initial?.objective ?? \'\')');
    expect(viewSource).toContain('useState(initial?.limits != null)');
  });

  it('鉴权降级失败 commit 分支与设备切换同口径 re-fence(codex P2)', () => {
    // resolveStartedDowngradeOrCommit 的降级/恢复 await 窗口可能换代(来源恢复或
    // 替换为 B)——鉴权降级失败(commit)分支必须像设备切换 commit 分支一样重跑
    // 有界 runGuard + genAt 核对,否则用等待前的空/旧目录校准草稿(codex review P2)。
    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);
    // 鉴权降级 commit 分支(agentAuthGateHint 之后)与设备切换分支(ensureDeviceAlive
    // 之后)之间,re-fence 循环位于各自 commit 判断之后;agentAuthGateHint 有 4 处,
    // 用 lastIndexOf 定位最晚的鉴权降级分支(在 resolveStartedDowngradeOrCommit 内)
    const authDowngrade = goalSlice.lastIndexOf('setGoalError(agentAuthGateHint(draft.agentKind));');
    expect(authDowngrade).toBeGreaterThan(-1);
    const afterAuth = goalSlice.slice(authDowngrade, authDowngrade + 800);
    expect(afterAuth).toMatch(/guardResult = await runGuard\(\);/);
    // re-fence 循环内每轮 runGuard 后同步设备检查(greptile P1):二次 runGuard 的
    // await 期间设备切换 → 提前 break,交设备切换分支按 started 语义降级,不再向
    // 旧设备 commit(会话落旧设备 + 当前页面无法接管 + 用户可能重复创建)。
    // 断言用位置比较(循环内 runGuard 之后、genAt break 之前有设备 break)。
    const runGuardIdx = afterAuth.indexOf('guardResult = await runGuard();');
    const deviceBreakIdx = afterAuth.indexOf('if (!ensureDeviceAlive()) break;');
    expect(runGuardIdx).toBeGreaterThan(-1);
    expect(deviceBreakIdx).toBeGreaterThan(-1);
    expect(deviceBreakIdx).toBeGreaterThan(runGuardIdx);
  });

  it('goal commit segment: started 后无裸 return,goal.set 先于本地同步(round-22 Spec P1-2/P1-3)', () => {
    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);
    expect(iCreate).toBeGreaterThan(iStarted);
    // started 可靠落账后到 createSession 之间:禁止 owner 中止与补偿式设备取消;
    // 唯一的 return 必须是「降级成功才 return」(downgrade-or-commit,独立 review round-22)
    const startedToCreate = goalSlice.slice(iStarted, iCreate);
    expect(startedToCreate).not.toMatch(/isCurrentOwner\(\)\) return;|abortIfDeviceSwitched/);
    expect(startedToCreate).toMatch(/if \(decision === 'downgraded'\) return;/);
    // started commit 段的 return 必须是 downgraded 分支(枚举全部 return;
    // 2 处 = 设备切换降级 + started 写盘后鉴权门禁降级,均降级成功才 return)
    const returns = startedToCreate.match(/return;/g) ?? [];
    expect(returns).toHaveLength(2);
    expect(startedToCreate).toContain('applyGuard(guardResult);');
    // 降级模式:started 失败与设备切换两处都 re-register phase precreated
    // (goal 区 phase:'precreated' 共 5 处:precreate 写盘 ×2 + 降级 ×3——
    // startedRecorded 失败降级 / 设备切换降级 / started 后鉴权门禁降级)
    expect(goalSlice.match(/phase: 'precreated',/g) ?? []).toHaveLength(5);
    // goal.set 先于 subscribe(session:)(本地同步属 settle 段)
    const iGoal = goalSlice.indexOf('maker.goal.set(');
    expect(iGoal).toBeGreaterThan(iCreate);
    expect(goalSlice.indexOf('subscribe(`session:${result.sessionId}`')).toBeGreaterThan(iGoal);
    // createSession 与 goal.set 之间无任何 owner/设备中止
    const between = goalSlice.slice(iCreate, iGoal);
    expect(between).not.toMatch(/isCurrentOwner\(\)\) return;|ensureDeviceAlive|abortIfDeviceSwitched/);
  });

  it('goal settle 段:goal.set 之后每处中止都是 owner + 设备双复核,切设备中止 settle(greptile P1)', () => {
    // goal.set 等待期间同账号可能切换设备:owner 检查拦不住,settle 若继续用旧
    // selectedDeviceId 会把设备 A 的会话写进当前页面并跳转设备 A 会话页,用户
    // 还会在设备 B 上重复创建——settle 每处中止必须并列设备复核(greptile P1)。
    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({'));
    // settle 段不再有裸 owner 中止
    expect(settleSlice).not.toMatch(/if \(!isCurrentOwner\(\)\) return;/);
    const dualChecks = settleSlice.match(/!isCurrentOwner\(\) \|\| !ensureDeviceAlive\(\)\) return;/g) ?? [];
    // subscribe / getSession(前+后) / catch / upsert / waitForPendingUploads 后 = 7 处
    expect(dualChecks.length).toBeGreaterThanOrEqual(7);
    // 跳转是 settle 最后一步:最后一个复核点之后无 await(无设备切换窗口)
    const lastCheck = settleSlice.lastIndexOf('!ensureDeviceAlive()) return;');
    expect(lastCheck).toBeGreaterThan(0);
    expect(settleSlice.slice(lastCheck)).not.toMatch(/await /);
  });

  it('goal settle 只登记本机预览,不把目标文案写成用户改名', () => {
    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({'),
    );
    expect(settleSlice).toContain('remoteSessionStore.setPendingTitlePreview(result.sessionId, session.title)');
    expect(settleSlice).not.toContain('persistRemoteGoalSessionTitle');
    expect(settleSlice).not.toContain('patchSessionMeta');
    expect(settleSlice).not.toContain('generateSessionTitle');
  });
});

describe('fast memory restore wiring (source locks)', () => {
  // Fast 记忆恢复的门控接线不变量(codex review P1):
  //  - 切/恢复 agent 两个恢复点的 agent 级门控必须只认**目标 agent** 的缓存能力表
  //    (targetAgentHasFast),不得直接用闭包里的 capabilities state(属于切换前 agent
  //    或冷启动 null);
  //  - 必须存在延迟恢复 effect:目标 caps 就绪后按 (agent, 来源, 模型) 记忆重评,
  //    通过才打开 fastMode——「永久清除合法记忆」与「恢复出目标不支持的 fast」
  //    两个故障形态都靠这对接线闭合。
  const newSource = newSessionSources;

  it('both restore sites gate on target-agent cached capabilities, never the closure state', () => {
    const gated = newSource.match(/isFastRestorable\(next\.agentKind, next\.providerId, next\.model, rowsNow, targetAgentHasFast\(selectedDeviceId, next\.agentKind\), rememberedFast\)/g) ?? [];
    expect(gated.length).toBe(2);
    // 恢复点不再直接消费 capabilities state 做门控
    const stale = newSource.match(/isFastRestorable\(next\.agentKind[^)]*capabilities\?\.hasFastMode/g) ?? [];
    expect(stale.length).toBe(0);
  });

  // 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.

  it('defers speed restoration until capabilities arrive and clears a revoked Ultrafast tier', () => {
    const rows = flattenProviderSections(buildMobileModelSections({
      agentKind: 'codex', providers: [{
        id: 'openai', name: 'OpenAI', connected: true, agents: ['codex'],
        source: 'builtin', auth: { method: 'oauth' },
        routing: { codex: { upstream: 'https://example.test', authStrategy: 'oauth-passthrough' } },
        models: { codex: [{ id: 'gpt', name: 'GPT', contextWindow: 1000,
          efforts: [], defaultEffort: null, supportsFastMode: true, supportsUltrafastMode: true }] },
      }],
    }).sections);
    let draft = newSessionDraft({ agentKind: 'codex', model: 'gpt', providerId: 'openai', fastMode: false });
    let capsKnown = false;
    let remembered: boolean | 'ultrafast' = 'ultrafast';
    const restore = () => restoreNewSessionFastPreference({
      selectedDeviceId: 'host', draft, draftMemory: { getFast: () => remembered },
      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);
    capsKnown = true;
    restore();
    expect(draft.fastMode).toBe('ultrafast');
    rows[0].model.supportsUltrafastMode = false;
    restore();
    expect(draft.fastMode).toBe(false);
    rows[0].model.supportsUltrafastMode = true;
    restore();
    expect(draft.fastMode).toBe('ultrafast');
    remembered = false;
    draft.fastMode = false;
    restore();
    expect(draft.fastMode).toBe(false);
  });
});

describe('compensatePrecreatedWorktree —— 设备切换补偿分阶段(独立 review P1-3)', () => {
  // 不得在远端目录已产生后只删账本(forget 删唯一 ledger 行 → 远端目录永久孤儿):
  // precreated 阶段必须 discard 获严格 ACK 才 forget;ACK 失败/未知 → 保留 ledger。
  const ack = { discarded: true as const };
  const base = {
    sessionId: 's1',
    recoveryKey: 'rk1',
    createdAt: 1,
    discard: () => Promise.resolve(ack),
    parseAck: (v: unknown) => (v && (v as { discarded?: boolean }).discarded === true ? { discarded: true as const } : null),
    forget: () => Promise.resolve(),
    release: null,
  };

  it('precreated + discard 严格 ACK → forget + release,返回 discarded', async () => {
    const forget = vi.fn(() => Promise.resolve());
    const release = vi.fn();
    const res = await compensatePrecreatedWorktree({ ...base, phase: 'precreated', forget, release });
    expect(res).toBe('discarded');
    expect(forget).toHaveBeenCalledTimes(1);
    expect(release).toHaveBeenCalledTimes(1);
  });

  it('precreated + discard ACK 非严格({discarded:false})→ 保留 ledger(不 forget),返回 retained', async () => {
    const forget = vi.fn(() => Promise.resolve());
    const res = await compensatePrecreatedWorktree({
      ...base,
      phase: 'precreated',
      discard: () => Promise.resolve({ discarded: false }),
      forget,
    });
    expect(res).toBe('retained');
    expect(forget).not.toHaveBeenCalled();
  });

  it('precreated + discard 抛错 → 保留 ledger(不 forget),返回 retained', async () => {
    const forget = vi.fn(() => Promise.resolve());
    const res = await compensatePrecreatedWorktree({
      ...base,
      phase: 'precreated',
      discard: () => Promise.reject(new Error('link down')),
      forget,
    });
    expect(res).toBe('retained');
    expect(forget).not.toHaveBeenCalled();
  });

  it('precreated + ACK 延迟到达且有效 → discard 后才 forget(顺序由 deferred 保证)', async () => {
    const d = deferred<unknown>();
    const forget = vi.fn(() => Promise.resolve());
    const pending = compensatePrecreatedWorktree({
      ...base,
      phase: 'precreated',
      discard: () => d.promise,
      forget,
    });
    await flush();
    expect(forget).not.toHaveBeenCalled(); // ACK 未到,绝不提前删账
    d.resolve(ack);
    const res = await pending;
    expect(res).toBe('discarded');
    expect(forget).toHaveBeenCalledTimes(1);
  });

  it('reserved(仅账本,无远端副作用)→ 直接 forget,不调 discard,返回 discarded', async () => {
    const discard = vi.fn(() => Promise.resolve(ack));
    const forget = vi.fn(() => Promise.resolve());
    const res = await compensatePrecreatedWorktree({ ...base, phase: 'reserved', discard, forget });
    expect(res).toBe('discarded');
    expect(discard).not.toHaveBeenCalled();
    expect(forget).toHaveBeenCalledTimes(1);
  });
});

describe('resolveStartedDowngradeOrCommit —— started 落账后设备切换处置(round-23 Spec P1-1/P1-2)', () => {
  // 降级成功 → 'downgraded'(recovery 可回收);降级失败 → 恢复 volatile 回 started
  // 后 'commit'——防 recovery 读到可 discard 的 precreated 对未知创建做 destructive
  // discard(破坏「started 绝不回收未知创建」不变量)。
  const base = {
    downgrade: () => Promise.resolve(true),
    restoreStarted: () => Promise.resolve(),
  };

  it('downgrade 成功 → downgraded,不调 restoreStarted', async () => {
    const restoreStarted = vi.fn(() => Promise.resolve());
    const res = await resolveStartedDowngradeOrCommit({ ...base, restoreStarted });
    expect(res).toBe('downgraded');
    expect(restoreStarted).not.toHaveBeenCalled();
  });

  it('downgrade 返回 false → commit,且恢复 volatile started', async () => {
    const restoreStarted = vi.fn(() => Promise.resolve());
    const res = await resolveStartedDowngradeOrCommit({
      downgrade: () => Promise.resolve(false),
      restoreStarted,
    });
    expect(res).toBe('commit');
    expect(restoreStarted).toHaveBeenCalledTimes(1);
  });

  it('downgrade 抛错 → commit,且恢复 volatile started', async () => {
    const restoreStarted = vi.fn(() => Promise.resolve());
    const res = await resolveStartedDowngradeOrCommit({
      downgrade: () => Promise.reject(new Error('storage down')),
      restoreStarted,
    });
    expect(res).toBe('commit');
    expect(restoreStarted).toHaveBeenCalledTimes(1);
  });

  it('downgrade 延迟到达且为 false → 恢复在决策后才发生(顺序由 deferred 保证)', async () => {
    const d = deferred<boolean>();
    const restoreStarted = vi.fn(() => Promise.resolve());
    const pending = resolveStartedDowngradeOrCommit({
      downgrade: () => d.promise,
      restoreStarted,
    });
    await flush();
    expect(restoreStarted).not.toHaveBeenCalled();
    d.resolve(false);
    const res = await pending;
    expect(res).toBe('commit');
    expect(restoreStarted).toHaveBeenCalledTimes(1);
  });
});

describe('new.tsx worktree 探测 effect 的离线起始态(#4046,源码契约)', () => {
  const source = readTextLf(resolve(__dirname, '..', '..', 'app', 'sessions', 'new.tsx'), 'utf8');

  it('起始 eligibility 经 initialWorktreeProbeEligibility 决定,不再硬编码 probing 后直接提前返回', () => {
    expect(source).toContain('initialWorktreeProbeEligibility({');
    expect(source).toContain("online: deviceLinkStatus === 'online',");
    expect(source).toContain('worktreeEligibilityRef.current = initialEligibility;');
    expect(source).toContain('setWorktreeProbe({ target, eligibility: initialEligibility });');
    expect(source).not.toContain("const probingEligibility: NewSessionWorktreeEligibility = { status: 'probing' };");
    // 提前返回条件与 fail-closed 语义不变:非 online 不发探测请求。
    expect(source).toContain("if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return undefined;");
  });

  it('离线起始态的恢复依赖 effect 依赖数组:链路 / 连接代次 / presence / 定时重探任一变化即重跑', () => {
    // recovering 不是终态,靠 effect 重跑回到探测;这几项漏掉任何一个,断网恢复后都会卡在
    // 「连接恢复中」。锁住依赖数组片段,补上 initialWorktreeProbeEligibility 单测覆盖不到的那一段。
    const effectStart = source.indexOf('initialWorktreeProbeEligibility({');
    expect(effectStart).toBeGreaterThan(0);
    const depsStart = source.indexOf('}, [', effectStart);
    const depsEnd = source.indexOf(']);', depsStart);
    const deps = source.slice(depsStart, depsEnd);
    for (const dep of [
      'connectionEpoch',
      'deviceLinkStatus',
      'presenceVersion',
      'worktreeDetectRetryNonce',
      'selectedDeviceId',
      'draft.workspaceKind',
      'draft.workingDir',
    ]) {
      expect(deps, `effect deps 应包含 ${dep}`).toContain(dep);
    }
  });
});

describe('closed saved model requires reselection', () => {
  const selected = { model: 'closed', providerId: 'prov-closed' };
  const visibilityOverrides = { 'codex:prov-closed:closed': false };
  const rows = [modelRow('replacement', ['medium'], 'medium')];
  const saved = hostRuntime('codex', selected.model, { providerId: selected.providerId, effort: 'high' });
  it('preserves the hidden pair during catalog reconciliation and remembered-agent restoration', () => {
    expect(resolveRecentModelAndProvider(rows, selected, 'codex', true, (rows).map((row: ProviderModelRow) => row.provider), visibilityOverrides)).toEqual(selected);
    expect(pickAgentDefaultRuntime({ providers: (rows).map((row: ProviderModelRow) => row.provider), agentKind: 'codex', hostRuntime: saved, modelRows: rows,
      currentEffort: 'medium', catalogReady: true, visibilityOverrides })).toMatchObject({ ...selected, effort: 'high' });
    expect(resolveNewSessionAutoDefault({ providers: (rows).map((row: ProviderModelRow) => row.provider), userTouched: false, appliedDeviceId: null, selectedDeviceId: 'devA',
      hostDefaultsSettled: true, hostRuntime: saved, modelRows: rows, rowsAgentKind: 'codex', catalogReady: true, visibilityOverrides,
      currentEffort: 'medium' })?.patch).toMatchObject(selected);
  });
  it('carries fresh visibility with its rows through the submit guard', async () => {
    const result = await resolveSubmitGuardCatalog({ cached: () => undefined, gen: () => 0,
      fetch: async () => ({ providers: [], modelVisibilityOverrides: visibilityOverrides }), buildRows: () => rows });
    expect(result).toMatchObject({ catalogKnown: true, rows, visibilityOverrides });
  });
});

// unit:执行页面原始回调与生产解析函数(不复制逻辑、不扫描参数字符串),断言最终计费来源。
// 原 Hook 用例没有覆盖 app/ 的接线;旧号池或 xd 无模型行,自定义来源与新号池同名且排在前。
describe('页面 Auto 校准和提交保留 Cindy 来源身份', () => {
  const auto = 'auto/group-1';
  const provider = (id: string, source: 'builtin' | 'organization' | 'user', ids: string[]) =>
    ({
      id,
      name: id,
      source,
      agents: ['pi'],
      routing: { pi: {} },
      connected: true,
      models: {
        pi: ids.map((model) => ({
          id: model,
          name: model,
          displayName: model,
          efforts: [],
          defaultEffort: null,
          contextWindow: 0,
        })),
      },
    }) as unknown as ProviderModelRow['provider'];
  const providers = [
    provider('custom', 'user', [auto]),
    provider('pool-new', 'organization', [auto]),
    provider('pool-old', 'organization', []),
    provider('xd', 'builtin', []),
  ];
  const rows: ProviderModelRow[] = providers.slice(0, 2).map((p) => ({
    provider: p,
    model: {
      id: auto,
      displayName: auto,
      efforts: [],
      defaultEffort: null,
      contextWindow: 0,
    },
  }));
  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 ({ 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(draft, guard);
      expect(result).toMatchObject({ model: auto, providerId: 'pool-new' });
    },
  );
});