Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
docs(setup): define three-screen interfaces and integration requirements (#2082)
Maxbd2e306a533d
diff --git a/docs/plans/2026-09-21-setup-three-screen-handoff.md b/docs/plans/2026-09-21-setup-three-screen-handoff.mdnew file mode 100644index 000000000..775a7a455--- /dev/null+++ b/docs/plans/2026-09-21-setup-three-screen-handoff.md@@ -0,0 +1,195 @@+# Setup 三屏重构实现清单(开发交接)++状态:待开发实现。Owner 于 2026-09-19 07:06 批准了桌面连接/设置对齐清单(含稳定框弹窗),2026-09-20 至 09-21 又将引导流程定为"三屏"版本(亮点 → 模型网关 → 助手启用),本文档是当前最终状态的统一交接。++## 0. 来源与基线++- 设计稿:`/Users/max/workspace/ai/avibe/avibe-docs/design_desktop.pen`(Pencil 原生编辑,禁止文本改 .pen)。最近一次原生保存 SHA-256:`3e5469a08e0b78f7a6e2f167b67f21afa657ed0f4c3e1b48ee2b97cf0383fc23`。+- 交互原型(模拟数据):`https://max-app.avibe.bot/show/ses36vg559de2/`(私有)。原型代码在 `/Users/max/.avibe/show/ses36vg559de2/src/`,其中 `pages/index.tsx` 为主流程、`GatewaySetup.tsx` 为第二屏、`KeyImport.tsx` 为发现提示与导入弹窗、`SetupHandoff.ts` 为转场动画、`setup-flow.css` / `gateway-flow.css` 为样式。原型是行为参考,设计稿是视觉参考。+- 已批准合同:`docs/plans/2026-09-19-desktop-connection-settings-alignment.md`(avibe 仓库 worktree `desktop-alignment-contract-20260919` 内同名文件),其中导入语义、稳定框、Settings 独立页、Workbench 侧栏/首页/Composer 条款继续有效。+- 实现基线:派发时刷新 `origin/master`(合同批准时为 `fd3734a99`),独立 worktree,走正常 PR/评审/CI 门禁。+- 验收环境:owner 指定的 `https://avibe-cloud-e2e-app.avibe.bot`;不重建已退役的本地 Incus 环境。++## 1. 范围总览++三屏引导流程(无侧栏壳):++1. 第一屏 欢迎/协作亮点:三助手接力演示 + 六个工作入口 + 「立即开始」。+2. 第二屏 添加模型提供商:顶部提供商卡片 → 模型网关 → 底部三个助手的路由图;发现提示胶囊;导入弹窗;添加来源弹窗。+3. 第三屏 选择/启用助手:安装/启用/默认模型路由/升级;「进入工作台」。++相邻已确认改动(同一设计轮,见第 11 节):Settings 独立页、Workbench 侧栏、首页与 Composer、浅色主题按钮配色。++不在范围:桌面套壳加载页、真实凭据扫描/导入的生产行为变更(复用现有 Model Gateway scan/apply)、Model Gateway 服务语义重构、macOS 菜单栏等 OS 层改动。++## 2. 全局壳、主题与锚点++- 壳:无 Workbench 侧栏。顶栏高 94(紧凑 78 / 移动 82);左侧品牌 = Avibe logo 图 + 「Avibe」(22/600) + 「Agent OS」(12, muted);右侧圆形语言按钮 44×44(Languages 图标),菜单含「简体中文 / English」+ 当前项对勾,外部点击或 Escape 关闭。Setup 页 logo 不加边框。+- 主题令牌:dark 背景 `#080812`、表面 `#11111c`、正文 `#f5f1e8`、次级 `#9ba3b8`、描边 `#ffffff24`、强调 `#5BFFA0`、强调浅底 `#5bffa014`;light 背景 `#f4f6fb`、表面 `#ffffff`、正文 `#0a0a14`、次级 `#5c6079`、描边 `#08081218`、强调 `#10B981`、浅底 `#10b98114`。浅色实心绿按钮文字与图标为白色;深色实心绿按钮文字 `#080812`。+- 卡片 hover:克制绿色描边 + 阴影 `0 2px 16px -4px #5bffa038`(预览最终值,设计稿旧值 blur 12 弃用),无位移/缩放。+- 主列宽:标准桌面 976;大屏(≥1600×950)1200;761–1020 为 `calc(100% - 48px)`;移动 `calc(100% - 40px)` 且 max 460。标题 h1 `clamp(32px,3.4vw,46px)`(大屏 50、紧凑 34、移动 30);副标题 `clamp(15px,1.35vw,18px)`(大屏 20、紧凑/移动 15/14)。+- 主行动锚点(三屏不变):CTA 区为三列网格(列宽 = 卡片宽),主按钮占中列第一行,高 56(紧凑 52)、圆角 12、字号 17(紧凑 16);返回按钮占中列第二行,同宽同高。三屏切换时主按钮坐标与尺寸不变。+- 动效偏好:尊重 `prefers-reduced-motion`;页面隐藏或暂停时停播;移动端切屏回顶部。++## 3. 第一屏 欢迎/协作亮点++- 文案:标题「各有所长,接力完成」/ 副「让 Claude Code、Codex、OpenCode 一起工作」;EN「Different strengths. One team.」/「Bring Claude Code, Codex, and OpenCode together」。+- 三张助手卡:Claude Code(PM)、Codex(开发)、OpenCode(测试)。卡内演示区播放工作字幕(如「撰写需求文档」→「需求文档已就绪」)与骨架内容;电路连线(含连接点圆点)在流程到达时脉冲;当前活跃卡高亮。+- 接力循环:横向流 0.75s、回程 1s,整循环约 8.7s;文字切换 0.25s;到达时对应卡高亮/完成态。+- 回路字幕「规划 · 开发 · 测试 · 交付」:圆角胶囊、90% 透明度、带遮罩底,垂直居中于回程线上(不贴容器底)。+- 六个入口:手机 APP、Slack、Discord、Telegram、飞书、微信;圆形 logo 容器 52(紧凑 48)、名称 12px、间距紧凑;文案「6个工作入口,随时随地安排工作」。手机 APP 项不用绿色高亮;自动轮播 hover 效果(2s 间隔),hover/focus 时暂停。Setup 状态下整块隐藏。+- 主按钮「立即开始」+ 右箭头;转场播放期间禁用。++## 4. 第二屏 添加模型提供商++- 文案:标题「添加模型提供商」/ 副「添加订阅或 API Key,由模型网关统一路由」。+- 顶部三张提供商卡:+ - 槽位 1–2 = 用户本机检测到/已配置的提供商(显示掩码 key);不足两个时按默认 OpenAI、Anthropic 补齐。+ - 槽位 3 恒为「添加更多」(虚线边框 + plus 图标 + 「订阅 / API Key」),通过它添加成功后右上角显示数量徽标。+ - 卡内三行信息:logo、名称、key 行。key 行文案:已连接 = 「API Key sk••••34d8」样式;检测到未添加 = 「检测到 API Key sk••••xxxx」;移动端隐藏「检测到 API Key」标签只显示掩码(单行省略)。+ - 状态样式:已添加/已选中 = 浅绿底 + 绿描边 + 克制阴影 + 右侧单个对勾;未添加 = 常规描边 + 右侧 plus。对勾位置:桌面右侧垂直居中;移动端右上角(6px 内缩、14px)。不出现「已添加 / Added」文字。+ - 检测到的候选默认自动选中;点击卡片切换选中(aria-pressed),选中 = 纳入本次导入批次。+- 路由图:顶部三卡 →(入线)→ 模型网关 →(出线)→ 底部三助手。连线样式与第一屏电路一致(1.5px 强调色、圆头、端点圆点 r2.5、脉冲动画);几何按卡片中心实测(resize 时重算)。+- 模型网关卡:宽 = 提供商卡宽,高 72(移动端自适应 min 72);居中两行文字「模型网关」(18/600) + 「模型一次接入,网关统一路由」(11, muted);不放 logo;有已连接提供商时进入 connected 强化样式。+- 底部三助手:Claude Code / Codex / OpenCode,logo + 名称(名称与第一、三屏一致);桌面高 84、移动 120(移动端三行:logo/名称/状态小字,见第 13 节待确认 1)。+- 摘要行(aria-live):有 pending 选择 = 「已选 N 个提供商:names · 仅复制,保留原配置」;已添加 = 「已添加 N 个提供商:names」带对勾;错误 = 「连接未完成,请检查配置后重试。」;无选择 = 「未选择提供商」。+- 发现提示胶囊(合同条款,设计稿含,当前预览未挂载,实现时恢复):+ - 居中、内容宽、桌面高 44、1px 描边、无阴影;与上下元素间距 20px;dark `#172F27`/`#30473E`,light `#EDF7F1`/`CEDFD5`(light 描边 `#CEDFD5`)。+ - 文案「发现 {{count}} 个可导入模型网关的 API Key」(count 来自真实候选数);轻按钮「查看并导入」;帮助链接「什么是模型网关?」;最右 X 关闭。+ - 帮助 tooltip 文案:「模型网关集中管理 API Key 和模型连接,为 AI 助手提供统一的模型入口。导入只会复制你选中的 API Key,原有配置会保留。」支持 hover、键盘 focus、移动端 tap;Escape/外部点击关闭。+ - 关闭不导入、不改就绪状态,保留布局槽位(主按钮不跳动);后续入口在设置-模型。+ - 移动端两行:第一行图标+全文+X,第二行「查看并导入」+帮助链接;≤360px 再收紧内边距与图标尺寸;英文长文案允许自然换行不截断。+- 导入弹窗「导入 API Key 到模型网关」:+ - 描述:「复制已有 API Key,方便在模型网关统一管理和使用,无需重新填写。仅导入你选中的项,原有配置会保留」。+ - 列表行:checkbox + 提供商 logo + 名称 + 掩码 key + 来源说明(如「Codex · 本机配置」);默认全选;空选择禁用导入按钮「导入选中的 N 项」。+ - 说明行:「仅导入 API Key,不包含订阅登录凭据。相同来源不会重复导入。」+ - 进度:「正在导入 N 个 API Key…」+「正在将选中的配置复制到模型网关」;完成:「已导入 N 个 API Key」+「原有配置已保留。助手连接状态不变」;完成数为累计值。+ - 有剩余:「还有 N 项未导入,可随时继续」+「继续选择」回选择态;「完成」关闭。+ - 语义:整批原子成功或整批失败+重试(保留选择与输入);不做部分成功;已导入来源不再作为候选;导入完成不等于助手就绪。复用现有 `/api/models/migration/scan` 与 `/apply` 及能力 gating,不复制 OAuth/订阅凭据。+ - 关闭后焦点回到触发按钮。+- 添加来源弹窗(主按钮无服务时点击 / 「添加更多」进入,标题「添加订阅或 API Key」/ 从添加更多进入为「添加更多模型提供商」):+ - 方式页签:已检测到(仅当存在未上榜的检测到来源时显示)/ 订阅 / API Key;页签切换不改变弹窗外框(稳定框,见第 7 节)。+ - 已检测到:多选列表(logo、名称、掩码、来源),已添加行禁用并显示「已添加」标记;说明「选择即可添加,无需重新填写;原有配置会保留。」+ - 订阅:仅 OpenAI(ChatGPT) 与 Anthropic(Claude);说明「前往服务商完成授权,无需在 Avibe 输入账号密码。」+ - API Key:默认八家按序 OpenAI、Anthropic、xAI、Gemini、DeepSeek、Qwen、Kimi、OpenRouter,真实 logo、统一容器与光学尺寸;「更多服务商」折叠内 Mistral、Cohere、Z.AI(含已配置项);输入框 placeholder `sk-demo-example`,空输入禁用主按钮。+ - 进度两阶段(保存→检查)对应文案「正在保存模拟配置…/正在检查模型连接…」(生产用真实阶段文案);失败错误框保留输入与选择,主按钮变「重试」。+ - 页脚:取消 / 主按钮(「添加选中的 N 项」/「前往 ChatGPT/Claude 登录」/「添加」)。+- 主按钮文案状态:有 pending 选中 = 「导入 N 项并继续」;失败后 = 「重试导入 N 项并继续」;已有服务 = 「继续,选择 AI 助手」;无服务 = 「添加订阅或 API Key」(点击打开添加弹窗);busy = 「正在连接…/正在检查连接…」并禁用。+- 返回按钮「返回介绍」(主按钮下方同宽)。+- 首次进入序列动画:顶部三卡 → 入线 → 模型网关 → 出线 → 底部三助手(约 1.1s);reset 可重播(预览控制,不随产品 shipped)。++## 5. 第三屏 选择/启用助手++- 文案:标题「选择你的 AI 助手」/ 副「启用助手,确认默认模型,即可开始工作」。+- 卡片结构:身份行(logo 30、名称 17/600、角色 11/700 右置、启用 Switch 仅 installed 时显示)→ 分隔线 → 状态 pill(已启用/未启用/未安装/安装中/升级中,圆点或 spinner)→ 描述行 → 底部动作区。+ - 描述行:未安装「安装 X,使用已添加的模型」;已启用「使用模型网关的默认路由」;已安装未启用「启用后即可使用已添加的模型」。+ - 动作:未安装 = 「立即安装」(outline + Download,安装中 spinner「正在安装…」);已启用且有路由 = 默认模型 chip(「默认模型」小字 + 模型名 + ChevronRight,打开路由弹窗);已安装未启用 = 「已安装,未启用」静态行(启用走身份行 Switch);有更新 = 「立即升级」(outline + ArrowUpToLine,可与已启用共存,升级中 spinner)。+ - 已启用卡高亮:绿描边 + 浅绿底 + 克制阴影(与第二屏已添加选中同款)。+- 默认模型路由弹窗「默认模型路由」:描述「所有已启用的助手共用。优先使用首选模型,不可用时按顺序尝试备用模型。」;行 = 提供商 logo + 模型名 + 「服务名 · 首选/备用 N」;上移/下移按钮(首尾禁用);单路由时说明「当前模型已设为首选,无需额外配置。添加更多来源后可设置备用顺序。」;页脚「添加模型来源」(回第二屏)+「完成」;关闭焦点回触发 chip。+- 主按钮「进入工作台」启用条件:存在 ready 服务且已设默认模型路由,且至少一个助手 installed+enabled;否则禁用。点击后才进入 Workbench 新建会话。+- 返回按钮「返回模型」(主按钮下方同宽);dark 下 hover 不变背景只变文字对比。+- 全部未安装场景:三卡均「立即安装」,主按钮禁用;用户可先回第二屏补模型来源再安装。+- 状态保留:返回第二屏再进入时,已添加/选中/启用/安装状态全部保留(09-20 修复过回退丢状态 bug)。++## 6. 转场动效++- 1→2(providers handoff):对第一屏三卡做快照,三卡收缩下移成为第二屏底部三助手位置;顶部三卡与模型网关自上方淡入压入;连线随后绘制。+- 2→3(assistants handoff):顶部三卡、模型网关与连线退场;底部三卡自下方顶起放大为第三屏卡片尺寸。+- 实现要点:快照 + FLIP 式插值(原型 `SetupHandoff.ts`);reduced-motion、暂停、页签隐藏时直接切换不播;移动端切换前回顶部;转场期间主按钮禁用且坐标不变。++## 7. 弹窗稳定框(合同条款,适用于第二屏三个弹窗)++- 同一弹窗在页签/状态切换时外框不变:标题、描述、页签、关闭、页脚锚定;中部内容区必要时滚动(长错误、提供商列表、授权说明)。+- 公共框属性参考:宽 568、内边距 24、圆角 16、间距 20;高度取该助手/该弹窗"较长常规表单"的常规高度(例:Claude 对可共用 588),并受视口约束;不同弹窗可有各自公共高度,同一弹窗各状态必须一致。+- 加载、凭据类型切换、授权进度、错误都套用同一外框;切换保留已填草稿与焦点;隐藏面板不保留可聚焦控件、不启动重复授权副作用。+- 移动端考虑键盘与安全区;不把单一绝对高度套用到全应用。+- 验收:同视口反复切换 订阅/API Key(及 API Key/Auth Token 类状态),标题、页签、外框、页脚不动;长内容可滚动、动作可达、输入存活。++## 8. 文案表(ZH / EN,走现有 i18n 资源)++| 位置 | 中文 | English |+| --- | --- | --- |+| 一屏标题/副 | 各有所长,接力完成 / 让 Claude Code、Codex、OpenCode 一起工作 | Different strengths. One team. / Bring Claude Code, Codex, and OpenCode together |+| 一屏按钮 | 立即开始 | Get started |+| 回路字幕 | 规划 · 开发 · 测试 · 交付 | Plan · Build · Test · Deliver |+| 入口文案 | 6个工作入口,随时随地安排工作 | 6 ways to work. Wherever you are. |+| 二屏标题/副 | 添加模型提供商 / 添加订阅或 API Key,由模型网关统一路由 | Add model providers / Add a subscription or API Key. Model Hub handles routing. |+| 网关卡 | 模型网关 / 模型一次接入,网关统一路由 | Model Hub / Connect models once. Model Hub handles routing. |+| 检测到/已连接 key 行 | 检测到 API Key … / API Key … | API key detected … / API Key … |+| 添加更多 | 添加更多 / 订阅 / API Key | Add more / Subscription / API Key |+| 摘要 | 已添加 N 个提供商:… / 已选 N 个提供商:… · 仅复制,保留原配置 | N providers added: … / N providers selected: … |+| 发现胶囊 | 发现 N 个可导入模型网关的 API Key / 查看并导入 / 什么是模型网关? / 关闭导入提示 | Found N API keys to import into Model Gateway / Review and import / What is Model Gateway? / Dismiss import notice |+| 导入弹窗 | 导入 API Key 到模型网关 / 导入选中的 N 项 / 正在导入 N 个 API Key… / 已导入 N 个 API Key / 还有 N 项未导入,可随时继续 / 继续选择 / 完成 | Import API keys to Model Gateway / Import N selected / Importing N API keys… / Imported N API keys / N remaining… / Review remaining / Done |+| 添加弹窗 | 添加订阅或 API Key / 添加更多模型提供商 / 已检测到 / 订阅 / 更多服务商 / 前往 ChatGPT/Claude 登录 / 添加 / 重试 / 取消 | Add subscription or API Key / Add more model providers / Detected / Subscription / More providers / Sign in with ChatGPT/Claude / Add / Retry / Cancel |+| 二屏主按钮 | 导入 N 项并继续 / 重试导入 N 项并继续 / 继续,选择 AI 助手 / 添加订阅或 API Key / 正在连接… / 正在检查连接… | Import N and continue / Retry importing N / Continue to assistants / Add subscription or API Key / Connecting… / Checking connection… |+| 返回 | 返回介绍 / 返回模型 | Back to introduction / Back to models |+| 三屏标题/副 | 选择你的 AI 助手 / 启用助手,确认默认模型,即可开始工作 | Choose your AI assistants / Enable an assistant, confirm its default model, and start working |+| 状态 pill | 已启用 / 未启用 / 未安装 / 安装中 / 升级中 / 已安装,未启用 | Enabled / Not enabled / Not installed / Installing / Updating / Installed, not enabled |+| 动作 | 立即安装 / 安装并启用 / 正在安装… / 立即升级 / 默认模型 | Install / Install and enable / Installing… / Update now / Default model |+| 路由弹窗 | 默认模型路由 / 首选 / 备用 N / 添加模型来源 / 完成 | Default model route / Preferred / Backup N / Add model source / Done |+| 三屏主按钮 | 进入工作台 | Open workspace |++## 9. 响应式规则++- ≥1600×950:主列 1200;h1 50、副 20;卡片 padding 28、logo 35;网关高 80;入口区 830 宽。+- max-height 1000 且 ≥761:紧凑档(主列 976、h1 34、卡高 262、CTA 高 44→动作区 52 等)。+- 761–1020:主列 `calc(100% - 48px)`,字号与 padding 收紧一档。+- ≤760(移动):一屏卡片纵排、电路与回路字幕隐藏;二屏三列小卡(logo/名称/key 三行居中)、网关窄列、底部助手纵排三行、胶囊两行、CTA 全宽纵排;三屏卡片纵排可滚动;切屏回顶部。+- ≤360:胶囊与卡片再收紧(图标 16/24、内边距 10)。+- 矮屏桌面(max-height 800):动作高 52、入口圆 48。+- 大屏垂直居中:内容超高时允许滚动,顶部留 `max(16px, (100dvh - 900px)/2)` 一类弹性留白。++## 10. 无障碍与键盘++- 切屏后焦点落到 h1(tabIndex -1);摘要、状态 pill、胶囊文案、进度用 aria-live。+- 卡片/页签/提供商按钮用 aria-pressed;Switch 带 label;图标按钮带 aria-label;tooltip 用 aria-describedby + aria-expanded。+- 弹窗焦点陷阱,关闭后焦点回触发元素;Escape 与外部点击关闭菜单/tooltip/弹窗(进度中不可关导入弹窗)。+- 非当前屏内容用 hidden/inert 屏蔽焦点与读屏。+- 预览控制条(场景选择、暂停、重置、模拟失败)仅原型使用,不随产品 shipped。++## 11. 相邻已确认改动(同轮设计,合同条款)++- Settings 独立页:196px 设置导航栏 + 880px 内容列(32 水平 padding)+ 40px 返回行;无 Workbench 侧栏与 248px 偏移;直链/深链同样独立布局;返回恢复来源会话与未发送草稿;初始设置未完成回引导。+- Workbench 侧栏:品牌整体点击进新会话首页,副标题「Agent OS · Workbench」;删除独立新建会话行;搜索在品牌下全宽(保留 Cmd+K),其下收件箱全宽;项目标题保留添加项目;Agents/Skills 选中低饱和填充细描边、无外 glow;Apps 与设置置底;设置图标 1:1、Apps 相应加宽(09-20)。+- 首页:标题「今天想搭点什么?」+ 打开项目/管理 Agents/建后台任务;「<助手名> 已连接,可以开始工作」仅在首次真实连接成功后出现一次。+- Composer 两行:上行文本;下行附件、语音、Agent、工作区控件,Send 居右;图标按钮 28×28、选择器触发 28 高;hover/focus 覆盖整个目标且无位移;首页首条消息前附件/语音即可用;草稿与选择跨选择器取消和 Settings 往返保留。+- 浅色主题:实心绿按钮白字白图标;侧栏 Apps 控件为软绿填充 `#10B98129` + 绿描边/图标 + 常规文字(非实心主按钮)。++## 12. 设计稿画板索引(design_desktop.pen)++| 内容 | 画板 |+| --- | --- |+| 一屏 | bi8Au / P8iLm0 / J0qaZ;响应式 Hw8U2、wgbz7、FYMoC、GQvuC |+| 二屏 | i3vw9 / ktRgC / lm7mN;已添加 F8RLgR / xNmhX / r1IQ0B;响应式 p9BBt、kmZ1h、bD9bh、FYbSi |+| 三屏 | ICidc / HR3ps / S3mLYc;hover mK2JX / X7N2Z / ZaXoW;可升级 I9Q8VD / QPdWU / pHiuw;停用 GjGqO / tyLMM;响应式 V23IKo、KEvip、a1Ten、UuTup |+| 导入与帮助 | cGYku(发现/选择/进度/完成)、m2wv6X(帮助与关闭态) |+| 稳定框弹窗 | Cifke / e3UyJ / siyGC(错误与重试示例) |+| 响应式规则 | eq9QT |+| Settings / 侧栏 / 首页 | r6G6P / imxrT / IVZQS;DkNTK / m1yENk / ZAP8R / OCacc / k2FY0;n0PzOn / h8OBx / bobPL |++## 13. 已知差异与待确认(实现前 owner 一句话确认)++1. 底部三助手是否带「未启用」小字:设计稿有、预览没有。建议跟预览(只留 logo+名称),设计稿后续同步。+2. 网关英文文案:预览为 Model Hub / Connect models once. Model Hub handles routing.;设计稿英文板为 Model Gateway / Gateway handles routing。建议跟预览 i18n 字符串,设计稿英文板后续同步。+3. 发现胶囊:合同与设计稿都要求,当前预览未挂载(KeyImport 组件存在但未渲染)。建议实现时按合同恢复于第二屏(有未导入候选且未关闭时显示)。+4. 「添加更多」卡边框:预览虚线、设计稿实线。建议跟预览虚线,设计稿后续同步。+5. 旧按助手连接弹窗系列画板(V0zHJ…、JaGjt…、Cifke…):三屏流程中 onboarding 不再按助手开连接弹窗;稳定框原则改用于第二屏三个弹窗。建议这些画板仅作为设置内连接管理参考,onboarding 不实现。++## 14. 验收清单++- 三屏切换:主按钮坐标/尺寸全程不变;返回保留全部状态;转场在 reduced-motion 下直接切换。+- 二屏:检测到候选默认选中且只有一个右侧对勾;切换选中不影响已添加底色;导入 N 项后卡变已添加样式、摘要与徽标计数正确;关闭胶囊后主按钮不跳动;tooltip 三种触发方式可用。+- 导入:空选择禁用;整批原子;失败重试保留选择;累计完成数;已导入不再出现;剩余可继续。+- 添加弹窗:页签切换外框不动;八家顺序与 logo;更多折叠;订阅仅 ChatGPT/Claude;空 key 禁用;错误保留输入。+- 三屏:安装/启用/升级/停用各状态独立呈现且只有一个加载指示;路由排序生效并共享;进入工作台 gating 正确;全未安装场景可走通。+- 响应式:1920×1080、1440×900、1366×768、390×844、375/320 窄屏、缩放与软键盘下无裁切、无横向溢出、动作可达。+- 主题与语言:dark ZH、dark EN、light ZH 对照设计稿;light EN 长文案不破坏布局。+- 相邻改动:Settings 直链独立布局且返回保留草稿;侧栏/首页/Composer 条款逐条对照。++## 15. 实现边界++- 独立 worktree、基于刷新后的 origin/master;保留无关本地改动。+- 复用现有 auth、Model Gateway scan/apply、媒体与路由基础设施;不做后端语义重构;缺展示字段时先定义最小兼容元数据。+- 所有新增用户文案走 `ui/src/i18n/en.json` / `zh.json`;不硬编码。+- 预览/演示数据只存在于原型;生产 UI 不显示模拟凭据说明。+- PR 走正常评审与 CI 门禁;合并需 owner 明确指令;验收在指定云环境。diff --git a/docs/plans/2026-09-21-setup-three-screen-implementation-plan.md b/docs/plans/2026-09-21-setup-three-screen-implementation-plan.mdnew file mode 100644index 000000000..f0ecfece3--- /dev/null+++ b/docs/plans/2026-09-21-setup-three-screen-implementation-plan.md@@ -0,0 +1,609 @@+# Setup three-screen rebuild — implementation plan++Status: **PR0 bounded repair; feature implementation not dispatched** (2026-09-21).+The owner's explicit merge authority covered #2065 only. Current orchestrator requests+from `ses8dhcc2zq62` authorize PR0 repair, not #2082 merge or feature implementation.+The owner reaffirmed on 2026-09-21 12:56 +08 that setup uses Model Hub and disabling it+belongs to Settings afterward. No unsupported/error/explicitly-disabled Direct setup branch+is part of the contract. At 13:19 +08 the owner ratified D10: reuse the existing migration+takeover feature; setup presents discovery/context and consumes confirmed results. Migration+confirmation, cleanup, custody, mode transition and recovery stay with their existing owner.+Neither decision grants feature/merge authority. D4/D9 routing and the corrected D11 transport+remain orchestrator-ratified technical mappings, with separate frontend/backend evidence.++Shared detail lives in `docs/plans/setup-three-screen/contracts.md` (C3–C6),+`copy-contract.json` (C1, selected takeover copy) and `ui/src/components/onboarding/setupFlow.ts`+(C2). The handoff remains unchanged user source. Owner D10 supersedes its copy-only,+unchanged-connection and atomic-rollback promises for this flow. Custody is settled; feature+start still requires separate authorization and contracts on master.++Sources and provenance:++- Handoff spec: `docs/plans/2026-09-21-setup-three-screen-handoff.md` (already tracked+ by PR0; preserved byte-for-byte against the dispatched head).+- Approved runtime/custody precedent: `docs/plans/model-hub-native-takeover.md`, especially+ Approved user flow (default runtime, no enable-confirmation, separate takeover consent).+- Approved contract: `docs/plans/2026-09-19-desktop-connection-settings-alignment.md`+ (worktree `desktop-alignment-contract-20260919`).+- Interactive reference: Show session `ses36vg559de2` — `pages/index.tsx`,+ `GatewaySetup.tsx`, `KeyImport.tsx`, `SetupHandoff.ts`, `setup-flow.css`,+ `gateway-flow.css`.+- Design source: `../avibe-docs/design_desktop.pen`, board index in the handoff §12.+- Product baseline: `origin/master` at `31c4e831b`, which is `a07acee02` plus the merged+ #2065. This is the initial planning baseline, not a claim about today's primary checkout.+ This repair re-read shipped owners from the assigned head `08b82658bb`; primary dirty+ files were not edited.++## 1. Goal++Replace today's two-step `/setup` (welcome → assistant connection) with the handoff's+three-screen flow — collaboration highlights → model providers → assistant enablement —+inside one sidebar-free shell whose primary action never moves. Default setup requires a+usable Model Hub candidate. Unsupported installation without a usable running Hub is a+recoverable environmental failure on the same flow, not an automatic Direct alternative.+Explicitly disabled configuration is a setup prerequisite failure, preserved without a+Direct completion or silent rewrite. Post-setup Settings remains separately owned.++The design is not a new surface bolted onto the old one: screen 1 already ships, screen 3+is a restructure of what ships, and screen 2 is a new composition of Model Hub APIs that+already ship. C6 defines explicit model-chain projection and controller/runtime ordering+against those owners. Owner-ratified D10 adopts existing migration takeover; setup does not+implement credential migration. Discovery cards/capsule/entry remain consumers of that feature.++## 2. Baseline and preconditions++- Fork every lane from a refreshed `origin/master` in its own worktree under+ `.worktrees/avibe/<branch>`, per `pr-delivery-loop` §0. No stacked PRs: each PR bases+ on `master` and declares unmerged dependencies in its body.+- Contracts (§5) are committed to `master` **before** any lane forks. A contract that+ lands after the fork is two divergent copies. This PR is that commit.+- **#2065 is merged** (squash `31c4e831b`, owner-authorized). Before merging it was+ verified at head `25de7e7d6`: a Codex pass comment naming that sha, the bot's `+1` on+ the PR body, 16/16 review threads resolved, CI 18/18 success, `mergeStateStatus: CLEAN`.+ It supplies exactly the surfaces this plan builds on: the 44px brand lockup and round+ language button, the `--ob-*` card-height/headline tier system in `onboarding.css`, the+ switch-in-identity-header card shape, the lifecycle chip's `onVisual` callback, and the+ action-anchor geometry specs.+- Model Hub is **default-on** since `06f444c13 feat(model-hub): enable Model Hub by+ default (#1917)` — `is_model_hub_enabled()` defaults to `"1"` with an explicit+ deployment override. Screen 2 is therefore a default path, not a flagged one. The+ capability projection (`capabilities.model_hub.enabled`) still exists. A disabled value+ holds setup at its configuration/recovery boundary; it does not select another journey (D5).+- Acceptance runs on the owner's designated cloud target+ <https://avibe-cloud-e2e-app.avibe.bot> (workspace `AGENTS.md`, 2026-09-18). The initial plan recorded+ `401 remote_access_login_required` unauthenticated; this repair made no remote probe. Its capability flag, gateway+ runtime health and backend modes must be read with credentials at acceptance time, and+ deploying to it needs explicit owner authority.++## 3. Reuse inventory (read before writing anything)++| Need | Existing owner on `origin/master` | State for this round |+| --- | --- | --- |+| Setup shell, brand, language | `ui/src/components/Wizard.tsx` (`.onboarding-shell`), `visual/BrandLogo.tsx`, `LanguageSwitcher.tsx` | shipped; design lockup refined by #2065 |+| Screen 1 story, cards, wires, loop caption | `steps/Welcome.tsx`, `onboarding/CollaborationStory.tsx`, `onboarding/collaborationTimeline.ts`, `onboarding/motion.ts` | shipped (#2048/#2052/#2065); adapts to the new shell |+| Six access entries | `onboarding/AccessTiles.tsx` | shipped; needs `hidden`/`inert` instead of unmount |+| Assistant cards, install/detect/enable | `steps/AgentDetection.tsx` (606 lines), `onboarding/AssistantRow.tsx`, `settings/BackendLifecycleChip.tsx` | shipped; restructured by screen 3 |+| Per-assistant connection dialog | `onboarding/BackendConnectionDialog.tsx` | leaves setup; existing Settings/backend Direct support remains unchanged |+| Discovery capsule + dismissal memory | `onboarding/ImportKeysNotice.tsx`, `lib/modelHubMigrationDismiss.ts` | shipped; C6 identifies copy and scan-ownership gaps before moving it to screen 2 |+| Import batch dialog | `settings/models/MigrationDialog.tsx`, `migrationScan.ts` (`importableKeys`, `isImportableKey`, `scanMigrationWhenEnabled`) | owner-ratified D10 reuse; minimal controlled-state/copy adaptation, one migration confirmation/apply/recovery owner |+| Add API key: vendor picker, observe → create | `settings/models/AddApiKeyDialog.tsx` (41 KB impl, 40 KB tests), `apiKeyVendors.ts`, `vendorMarks.ts`, `vendorGlyph.tsx` | shipped; needs its form extracted so a tabbed stable frame can host it (D2) |+| Subscription sign-in | `modelsApi.startOAuth/getOAuthStatus/submitOAuth/cancelOAuth`, `settings/models/OAuthConnectDialog.tsx`, `settings/oauth/OAuthFlowParts.tsx` | shipped; subscription tab drives it |+| Added providers, masked keys, vendor identity | `modelsApi.listSources()`, `Source{vendor, display_name, masked_credential, account_label, state, models}` | shipped; screen 2's connected cards |+| Detected candidates with vendor, mask and source label | `modelsApi.scanMigration()`, `MigrationItem{id, vendor?, display_name?, masked_credential?, masked_detail, backend, source_paths?, required_backends?, notes_key?, proposed_action}` | shipped; screen 2's detected slots and import rows |+| Per-backend route read/write | `modelsApi.getAgentSources/putAgentSources/getAgentChain/putAgentChain/previewAgentChain`, `settings/models/RouteChainDialog.tsx`, `routeChainDraft.ts` | shipped; **there is no global route object** — see C6 and D4 |+| Gateway engine lifecycle | `settings/models/gatewayAdoption.ts` (`resumeGatewayAdoption`) over `runtimeLifecycle.ts` (`resumeInstallAndStartRuntime`, `installRuntimeUntilSettled`, `installAndStartStep`, `runtimeCanAttemptInstall`), plus `RuntimeNotStartedAction`, `InstallGatewayDialog`, `EnableGatewayDialog` | shipped primitives; neither helper preflights support, adoption skips already-Hub runtime checks and never changes mode. C6 defines required composition; D3 reuses approved automatic active-entry setup |+| Capability gate | `settings/models/featureFlags.ts`, `useModelHubCapability.ts`, `ModelHubCapabilityGate.tsx` | shipped |+| Wire drawing pattern | `settings/models/SupplyGraph.tsx` (measures `[data-source-id]` → `[data-agent-backend]`, `xl:block` only) | shipped; screen 2 needs vertical fan-in/fan-out at every width, so a new component reusing the same wire tokens rather than a bent `SupplyGraph` |+| Geometry and behavior harness | `ui/e2e/onboarding-fidelity/{fixture.tsx, support.ts, geometry.spec.ts, connections.spec.ts, loop.spec.ts, hub-ownership.spec.ts}` | shipped; `serveModelHub` already mocks scan/apply and must grow sources/runtime/agents routes |+| Theme tokens and guards | `ui/src/index.css` token scale, `ui/scripts/glowScale.test.mjs`, `npm run validate:theme` | shipped; no new literal colors |+| Onboarding behavior scenarios | `tests/scenarios/auth_setup/catalog.yaml` + `test_auth_setup_scenarios.py` | shipped; must be updated with the flow change (repo `AGENTS.md` §7) |+| Vendor logo artwork | `settings/models/vendorMarks.ts` — openai, anthropic, xai, gemini, deepseek, qwen, kimi, openrouter, mistral (+ monogram fallback) | shipped as inline paths; **no binary assets and no new dependency** |+| Vendor catalog and its order | `vibe/data/api_key_vendors.json`, tracked jointly with `vibe/model_hub_runtime/api_key_vendors.py`: `openai, anthropic, xai, gemini, deepseek, qwen, kimi, openrouter, zhipuai, mistral, groq, together, fireworks` | shipped; the first eight are exactly the contract's primary row. Cohere exists only as a prototype fixture (D7) |++## 4. Delta by area++### 4.1 Flow shell and state machine (new)++`Wizard.tsx` today holds `step: 'welcome' | 'agents'` and renders one step at a time, so+leaving a screen destroys its state — the class of bug the handoff §5 already records+("09-20 修复过回退丢状态"). The new shell:++- keeps all three screens mounted and gates them with `hidden` + `inert` (handoff §10),+ which retains local drafts. Hidden/inert does not suspend effects: C2 gates screen activity,+ polling and authorization; only the active screen may publish actions or navigate;+- renders **one** primary action and **one** Back button itself, so the "coordinates and+ size never change" invariant is a property of the tree instead of an agreement between+ two stylesheets. The active screen feeds `SetupAction` (`labelKey`, optional `labelArgs`, `disabled`, `busy`, `icon`) and exposes+ `activate()` through a ref — the reference's `onActionChange` + `GatewayHandle` shape;+- owns D11 config/bootstrap on active provider entry with enabled capability and saved runtime intent. Intro mount+ is read-only; config/readback, confirmed controller start and runtime preparation remain+ distinct outcomes. No bootstrap expansion for disabled/Direct setup;+- passes capability, saved `model_hub.enabled` and the existing runtime `RegionRead` through C2 with the shared retry+ callback. Runtime errors/support never change page sequence or saved modes;+- owns the flow state that must survive navigation (pending selection, imported count,+ model-ranked route draft). Server-owned install/enable facts are re-read, not copied into+ `SetupFlowState`; pass `flowState` and React `setFlowState` through C2, using functional+ updates so asynchronous completions preserve other screens' edits;+- moves focus to the screen's `h1` (`tabIndex={-1}`) on every screen change and scrolls+ to top on phones;+- keeps platform recovery (`SetupPlatformRecovery`) and the final `setup_completed` write.+ Hub model recovery follows C6; `SetupModelRecovery` remains its shipped Direct owner and+ is not repurposed to bypass Hub setup.++### 4.2 Screen 1 — collaboration highlights++Mostly shipped. Delta: the CTA leaves `Welcome.tsx` for the shell; the CLI detection that+`Welcome.start()` runs today (`api.detectCli` per assistant) stays on the transition and+is re-verified when screen 3 becomes active; `AccessTiles` becomes `hidden`/`inert` off screen 1+instead of unmounting; the three story cards become the handoff snapshot source.++### 4.3 Screen 2 — model providers (new, the bulk of the work)++Composition, top to bottom: three provider cards → inbound wires → gateway card →+outbound wires → three assistant destinations → summary line → reserved capsule slot.++- **Slots.** 1–2 are providers detected on this machine or already added; when fewer than+ two are known, fill with OpenAI then Anthropic. Slot 3 is always "Add more" (dashed+ frame, plus glyph, `订阅 / API Key`), and carries a count badge of what was added+ through it.+- **Card content.** logo + name + key line. Key line: added → `API Key sk••••34d8`;+ detected-not-added → `检测到 API Key sk••••xxxx`; phones drop the label and keep the+ mask. Data comes from `Source.masked_credential` / optional `MigrationItem.masked_credential`;+ use `masked_detail` for legacy scan rows as C6 specifies. These are render examples, not+ fixture values to ship; never mask or fabricate credentials client-side.+- **Card state.** added/selected → mint wash + mint border + restrained shadow + one+ check on the right (desktop: vertically centred; phone: top-right 6px/14px); not added+ → ordinary border + plus. No "已添加/Added" text on a card. Detected unblocked consent groups start+ selected according to server flags; clicking toggles the complete linked group through C6,+ never one key of a backend. Provider identity alone is not key/source identity.+- **Wires and gateway card.** 1.5px accent, round caps, r2.5 endpoint dots, pulse on+ arrival; geometry re-measured from real card centres on resize. Gateway card is one+ provider-card wide, 72 high (phone: min 72), two centred lines, no logo, and takes a+ connected treatment once a provider is ready.+- **Summary line** (`aria-live`): pending selection / added / error / none, with the+ C1 selected takeover copy; counts/status follow the existing migration owner, with no copy-only guarantee.+- **Capsule.** `ImportKeysNotice` moves here, keeping its persisted non-nagging+ dismissal. Count only keys in complete unblocked key-only groups (C6), with blocked+ detections still visible for explanation; give it a reserved slot so dismissing it+ cannot move the primary action.+- **Import dialog.** Follow C6's full-scan, transitive backend consent grouping. Cards,+ capsule and Detected tab share `providerSelection`; L2 must adapt/extract the existing+ `MigrationDialog` owner because its shipped props keep local state. Preserve blockers and+ linked rows outside the entry filter. API-key-only setup cannot submit mixed OAuth groups.+ Owner-ratified D10 delegates primary/Detected actions to that feature's review with the+ exact consequence and Not now / Start migration; only its explicit confirmation applies.+ Setup/L2 adapts presentation/context and consumes confirmed results; it owns no migration+ coordinator, cleanup, custody/mode transition, rollback or retry engine. Setup entry, runtime+ preparation, selection and normal navigation do not consent to takeover. On a confirmed+ receipt, count `applied` once and refresh real scan/sources/supplies. Existing `onApplied(0)`+ can be an error-triggered refresh, not completed takeover; preserve owner errors/recovery.+ No second mode PATCH follows successful apply, and migration success alone is not readiness.+- **Add-source dialog.** One stable frame (C5) with three methods: Detected (only when+ unlisted candidates exist; complete-group selection; required rows/blockers stay visible),+ Subscription (OpenAI/ChatGPT and Anthropic/Claude, using the shipped subscription+ vendor/custody options; C6 names the actual producer, not an absent capability-list API), API Key (the extracted vendor form:+ eight primaries in catalog order, `更多服务商` collapsed holding the catalog's+ remainder, empty input disables the action). The key field keeps the extracted shared+ form's own treatment; the prototype's `sk-demo-example` placeholder and its+ "do not enter real credentials" line are preview-only and ship nowhere (C1's rules,+ handoff §15). Progress follows real stages; failure keeps drafts, and unknown writes are reconciled+ before retrying. Read `SourceCreated` / `OAuthResult.created` and refresh server facts as C6+ requires; never create a source twice after OAuth success.+- **Primary action states.** `查看 N 项并继续` / `查看 N 项迁移状态` open the+ shared confirmation/recovery; `继续,选择 AI 助手` continues only when no pending apply+ needs review; `添加订阅或 API Key` opens Add; connecting/checking states disable it.+ These actions delegate migration work to the existing feature. Selecting cards never applies credentials.+- **Bootstrap/runtime.** With capability and saved runtime intent enabled, the shell's active provider-entry owner+ uses D11's CSRF-aware JSON POST `{}`, HTTP/body validation and uncached GET/readback before+ connection/start calls. Unknown writes need persistence reconciliation, not a cached GET+ or empty `mutateConfig([])`. Fresh config is installed in shell state; direct fetch does+ not clear ApiContext cache or emit convergence. Reuse a running controller or start only+ a confirmed stopped one, then read runtime. Controller startup itself owns the first+ runtime recovery (`_recover_runtime_owners()` → `recover_runtime_intent()`), including+ server-side installer admission, so the browser observes that outcome and requests+ admitted recovery only when the engine is still missing. D3 preflights every+ browser-initiated potentially installing path, ensures admitted runtime and reads back+ running health; no second unconditional lifecycle call follows a successful recovery.+ Unsupported/non-running keeps providers, drafts, Back, recheck and C1's installation-guide+ action. Errors stay errors; successful retry resumes the same flow. Healthy running Hub+ reads/routes and Continue remain usable despite unsupported install admission. No extra+ install-confirmation dialog, automatic Direct bypass or credential takeover.+- **First-entry sequence** (~1.1s): cards → inbound wires → gateway → outbound wires →+ destinations. The reference's reset/replay control is preview-only and does not ship.++### 4.4 Screen 3 — choose and enable assistants++Card becomes: identity row (logo 30, name 17/600, role 11/700 trailing, enable Switch+only when installed) → divider → status pill → description → action row.++- Status pill: 已启用 / 未启用 / 未安装 / 安装中 / 升级中, with dot or spinner — exactly+ one loading indicator per card while an operation runs.+- Description follows the state: not installed / enabled / installed-not-enabled.+- Actions: `立即安装` (outline + Download, spinner `正在安装…`) → `api.installAgent` then+ re-detect; routed candidate chip (`默认模型` + model name + ChevronRight) → route dialog;+ installed/enabled but unrouted (including Direct) → configure-route action, equally reachable;+ `已安装,未启用` static row (enabling belongs to the identity Switch); `立即升级`+ (outline + ArrowUpToLine) through `BackendLifecycleChip`'s `onVisual`, coexisting with+ the enabled state.+- Enabled card wears the same mint treatment as screen 2's added cards.+- **Default model route dialog**: shared ordered list, `提供商 logo + 模型名 + 服务名 ·+ 首选/备用 N`, up/down with first/last disabled, single-route note, footer+ `添加模型来源` (→ screen 2) + `完成`, focus back to the chip.+ The rows remain model-ranked as the handoff requests. C2 retains `(source_id, model_id)`+ draft rows; no source-order write can claim to save that list. C6/D4/D9 specifies builtin+ setup Agent targets, exact menu-model identities, per-target membership projection and+ readback/retry. Custom Agents with other menu models are untouched; same-key shared impact+ is disclosed. Fresh/empty targets use existing catalog/hop editors with explicit selection.+ Divergent routes are displayed without an opening write; a dirty shared draft and its+ target baselines survive navigation. Done without an edit is a no-op; an explicit reorder+ freezes changed automatic chains and requires the existing follows/frozen explanation.+- **Per-assistant Direct dialogs leave setup.** Keep their separate Settings/backend owner+ untouched. Setup always opens Hub configuration/recovery; disabled configuration exposes+ C2's prerequisite boundary, never native-auth completion. Routing access needs no route.+- All-uninstalled case: three `立即安装` cards, primary action disabled, and the user can+ go back to screen 2 to add sources first.++### 4.5 Readiness gate and completion++`Wizard.complete()` today requires a per-backend `entry_eligible` connection, starts the+service only from a confirmed stopped state, filters OpenCode agents by+`readOpencodeSetupRoutes`, preserves a usable default Agent, and writes `setup_completed`+last. D11 proves config persistence then confirmed controller startup on active provider+entry before Hub reads. Completion reuses confirmed-start recovery if the controller later+stops. Disabled gateway setup does not bypass providers or inherit Direct completion. Startup does not require installed assistants or sources.+The new gate preserves default/completion ordering and backend permission checks and replaces the route+input with C4's correlated named-Agent predicate: the same enabled/non-archived Agent has an+installed/enabled backend, running Hub runtime, a runnable own model/route and confirmed+application state. Source health, another backend's order and a local draft cannot satisfy+separate parts of the gate. Preserve a usable global default, otherwise select and read back+an available named Agent; write/read back `setup_completed` last. Re-pin the affected+`WizardCompletion.test.tsx` invariants deliberately. The all-backend correlation is new L3+orchestration, not behavior today's OpenCode helper already provides. Installation support+does not change this Hub requirement: no usable running Hub means enabled setup cannot+complete. Recheck/guide/Back remain available. CLI presence is corroborated through the+existing generation owner — `createAgentCollectionReadAuthority.refresh()`, which runs+`refreshAgentPresence()` (`?refresh_cli_presence=1`) and then a generation-controlled list+read — after an in-wizard install or path change and before completion; a cached+`listAgents()` snapshot or a superseded/failed refresh is not readiness evidence. Disabled+configuration also holds setup,+preserving saved preferences/custody and existing management boundaries; it never creates+Direct completion. C4 records this owner-ratified known-by-design boundary, not a review waiver.++### 4.6 Dialogs and the stable frame++Handoff §7 / C5 applies to all three screen-2 dialogs: one frame per dialog across its tabs+and states (568 wide, 24 padding, 16 radius, 20 gaps, a common height taken from the+longer ordinary form, viewport-bounded), anchored title/description/tabs/close/footer,+scrolling middle, drafts and focus preserved across tab changes, no focusable controls+and no duplicate auth side effects in hidden panes, phone keyboard and safe-area handled.+Acceptance is the repeated-tab-switch test, not a height transition.++### 4.7 Motion and handoff++Port `SetupHandoff.ts` to `ui/src/components/onboarding/setupHandoff.ts`: snapshot the+outgoing cards, FLIP them to the incoming positions, retire the provider stage on 2→3.+1→2 shrinks the story cards into the destination row while the provider cards and gateway+press in from above and the wires draw after; 2→3 lifts the destinations into full+assistant cards. Bail out to an instant switch under `prefers-reduced-motion`, a hidden+page, or a paused preview; scroll to top on phones before switching; the primary action+stays disabled and unmoved throughout.++### 4.8 Theme tokens and responsive tiers++No new literal colors: the handoff's hex values map onto the existing token scale, and+missing tokens are added to `index.css` rather than hardcoded (`validate:theme` and+`glowScale.test.mjs` guard this). Card hover is the restrained mint border plus+`var(--ob-active-shadow)` — already shipped and backed by `--shadow-glow-onboarding-mint`,+whose blur/spread/alpha follow the theme — with no translate or scale. The handoff's hex+value is a design reference, never a CSS literal; a lane that needs a value the scale lacks+adds a token instead of pasting the hex.++Extend #2065's `--ob-*` tier system to all screens under C3's existing media-query bands.+Map the handoff's desktop/phone measurements into those tokens; do not independently add+its differently numbered breakpoints in a screen stylesheet. Where exact design fidelity+requires changing a band, L1 must reconcile C3 and geometry fixtures with the orchestrator+before distributing it to L2/L3.++### 4.9 i18n++C1 (`docs/plans/setup-three-screen/copy-contract.json`) is the proposed copy table and the only+source of key names; handoff §8 is where its strings came from. New namespaces:+`onboarding.flow.*` (L1), `onboarding.providers.*` and `onboarding.import.*` (L2), and new+`onboarding.setup.*` / `onboarding.route.*` leaves (L3). Six shipped strings change: the four+welcome/access ones are L1's, the two setup headings are L3's. The capsule keeps+`settings.models.importNotice.*` for the discovery sentence, help link and dismissal label,+and the import dialog keeps `settings.models.migration.{blocked,errors,notes,source}.*` for+the explanations it renders, while setup chrome reads `onboarding.import.*`. `_migration_copy`+records D10's owner-ratified takeover copy and the delegation boundary. D8 allocates setup+copy scope; the minimal shared-owner adaptation remains future L2 work, preserving Settings+rendering and behavior. No display string is hardcoded in a component.++### 4.10 Accessibility++Focus to `h1` on screen change; `aria-live` on summary, status pill, capsule and progress;+`aria-pressed` on cards, tabs and provider buttons; labelled Switches and icon buttons;+tooltip via `aria-describedby` + `aria-expanded`; dialog focus trap with focus restored to+the trigger; Escape and outside click close menus, tooltips and dialogs (the import dialog+is not closable mid-progress); non-current screens `hidden`/`inert`.++## 5. Contracts proposed by PR0++PR0 carries six boundaries with D10's custody choice settled. Feature dispatch still requires+separate owner authorization and contracts on master; no lane may reinterpret them independently:++- **C1 Copy** → `docs/plans/setup-three-screen/copy-contract.json`. Allocated+ key names, the six shipped strings they change, and the existing strings they reuse (fixture metadata);+ validated for zh/en parity, complete `_one`/`_other` families on every `{{count}}`+ string, no nested-before-literal collision and identical placeholders per key. Key names+ are allocated across lanes; migration wording follows owner-ratified D10 and its existing feature owner.+- **C2 Flow interface** → `ui/src/components/onboarding/setupFlow.ts`, with+ `setupFlow.test.ts` covering sequence, navigation and actual React consumption of shared+ state, including a late update after another screen changes the route draft.+- **C3 Geometry and DOM hooks** → `contracts.md` §C3: the single shell-rendered anchor+ pair, the reserved capsule slot, the class names the handoff snapshots read across+ screens, and the tier rule (consume `--ob-*`, restate inside the existing bands, never+ invent a new one).+- **C4 Entry gate** → `contracts.md` §C4: the correlated candidate predicate and its producers, what stays+ unchanged in `complete()`, what is removed, the Hub-required configuration boundary, and which+ `WizardCompletion.test.tsx` invariants are deliberately re-pinned.+- **C5 Stable frame** → `contracts.md` §C5.+- **C6 Data mapping** → `contracts.md` §C6, field by field with a producer and a consumer+ per row, for both new screens.++## 6. Lanes and file ownership++| Lane | Executor | Owns | Must not touch |+| --- | --- | --- | --- |+| L0 contracts | orchestrator; current repair delegated to this executor | `docs/plans/2026-09-21-setup-three-screen-*.md`, `onboarding/setupFlow.ts`, the C1 fixture | product behavior |+| L1 shell + intro + motion | codex | `Wizard.tsx` (flow machine region), `steps/Welcome.tsx`, `onboarding/setupHandoff.ts`, `onboarding.css` shell/tier/CTA sections, `AccessTiles.tsx`, `ui/e2e/onboarding-fidelity/{fixture.tsx,support.ts,geometry.spec.ts,loop.spec.ts}`, i18n `onboarding.flow.*` and the four changed welcome/access strings | screen 2/3 internals |+| L2 providers screen | claude | new `onboarding/providers/**`, new `onboarding-providers.css`, `ImportKeysNotice.tsx`, the `AddApiKeyDialog` form extraction, `MigrationDialog`'s minimal controlled-state/copy adaptation and shared grouping reuse, new `ui/e2e/onboarding-fidelity/{provider-support.ts,providers.spec.ts}` and `hub-ownership.spec.ts`, i18n `onboarding.providers.*` / `onboarding.import.*` | `Wizard.tsx` outside the screen registry entry it adds last, screen 3 files, migration backend/cleanup/custody/recovery semantics, `onboarding.css`, L1's `fixture.tsx` / `support.ts` / `geometry.spec.ts` |+| L3 assistants + gate | codex | `AssistantRow.tsx`, `steps/AgentDetection.tsx`, new `onboarding/DefaultRouteDialog.tsx`, new `onboarding-assistants.css`, `Wizard.tsx` `complete()` region, `ui/e2e/onboarding-fidelity/connections.spec.ts`, i18n `onboarding.setup.*` / `onboarding.route.*` and the two changed setup headings | screen 2 files, `onboarding.css` shell sections |+| L4 scenarios + acceptance | codex | `tests/scenarios/auth_setup/**`, acceptance evidence, owner checklist | UI implementation |++Shared-touch files and the rule for each: `ui/src/i18n/{en,zh}.json` — key namespaces are+frozen by C1, each lane appends only inside its own namespace object, and the second lane+to merge rebases rather than resolving by hand. `Wizard.tsx` — L1 owns the flow machine,+L3 owns `complete()`, L2 owns only its registry entry. CSS — one file per screen so no two+lanes edit the same stylesheet; `onboarding.css` stays L1's.++Division of labor follows the default: claude takes the dialog-heavy, interaction-dense+provider screen; codex takes the shell/motion rigor and the readiness gate, where a wrong+predicate strands a first-run user.++## 7. Sequencing and PR plan++```+D1 (#2065, merged) ──► PR0 contracts ──┬─► PR1 shell+intro+motion (L1) ──► PR3 assistants+gate (L3) ──┐+ └─► PR2 providers (L2, parallel) ─────────────────────────────┴─► PR4 scenarios+acceptance (L4)+```++- **PR0** (four documents/fixtures + type module and consuming test): commit the handoff doc, this plan, the C1 copy+ fixture, `contracts.md`, `setupFlow.ts` and its consuming test. Merging it first is what makes the parallel lanes safe, and it+ carries the planning sources in the repository; preserve any divergent primary-checkout edits.+- **PR1** (L1) is behavior-preserving infrastructure: the screen machine in the new shell,+ one shared action pair, the handoff, the tier extension, and the geometry specs that hold+ the anchor invariant. It ships without screen 2 and without changing readiness; the interim+ registry must not expose an empty providers step just because final C2 names one.+- **PR2** (L2) starts in parallel with PR1, because everything it owns — the stage, the+ dialogs, the capsule move, the shared API-key form extraction — is new files plus shared-owner+ adaptations, and it builds against C2 with its own test harness. It declares+ `requires #PR1 merged first`, and its one `Wizard.tsx` registry line plus its fixture+ integration land as a final commit after PR1 is on `master`. D10 and C6 bootstrap/runtime+ composition are ratified; feature authorization and PR0-on-master still gate dispatch.+ No stacked PR: the base stays `master`.+- **PR3** (L3) forks after PR1 merges, using the orchestrator-ratified D4/D9 mapping. It rewrites the assistants+ screen and `complete()`, and PR1 rewrites the machine around `complete()` in the same+ file; two lanes editing one restructuring is a conflict that is not mechanical to resolve.+- **PR4** (L4) updates `tests/scenarios/auth_setup/catalog.yaml` and its harness cases for+ the new flow, and carries the acceptance evidence.+- Every PR: non-draft, `--base master` verified by reading the PR back, exact-head Codex+ review, zero unresolved threads, CI green, one durable `--forever` combined PR/CI watch+ with `--timeout 0` per `background-watch-hook`, and the review-loop circuit breaker.+ No merge without explicit owner instruction. The CI workflow name in this repository is+ `lint`; it produces every job a check list shows.++## 8. Validation++- Per lane: focused vitest suites; `npm run build`; `npm run validate:theme`;+ `typecheck:tests`; `ruff check` on any changed Python; `pre-commit run` on changed files.+- Behavior: the onboarding fixture harness (`ui/e2e/onboarding-fidelity`) extended to mock+ `/api/models/sources`, `/api/models/runtime/status` and `/api/models/agents/*` beside the+ existing scan/apply routes, asserting rules rather than copied numbers — anchor equality+ across three screens × two languages × six viewports, capsule dismissal leaving the action+ in place, stable-frame tab switching, handoff bail-out under reduced motion, phone+ scroll-to-top, no horizontal overflow.+- Cross-boundary: at least one end-to-end case that pierces shell → screen 2 → screen 3 →+ `complete()` with real (non-ASCII) data, since two mocked halves prove nothing about the+ boundary.+- Migration consumption: L2 tests cards/capsule/Detected → the existing complete-group+ confirmation → confirmed receipt → refreshed source/supply presentation. Verify no apply+ from selection/navigation/runtime start, Not now preserves native state, mixed OAuth groups+ remain blocked for setup, zero/error callbacks do not claim success, and Settings behavior+ survives the controlled-state/copy adaptation. Recovery stays with the existing feature.+- Backend: `tests/scenarios/auth_setup` closed-loop cases updated in PR4, with scenario IDs+ visible in the tests and the PR bodies.+- Acceptance: the owner's cloud target, with a ~10-minute checklist derived from handoff §14+ (three-screen anchors, selection/import/badge, dialog stability, install/enable/upgrade,+ route ordering, gating, six viewports, dark ZH / dark EN / light ZH / light EN).+ Verification is behavioral — driving the deployed app — never reading version strings.++## 9. Risks++- **`AddApiKeyDialog` extraction.** 41 KB of implementation and 40 KB of tests sit behind+ the form screen 2 needs. Mitigation: extract the form without changing the Settings+ dialog's public behavior, keep its existing suite green as the regression fence, and run+ the whole models suite in L2.+- **Gate rewrite on a stateful instance.** The acceptance environment preserves state, so+ backends there may be in Direct mode with native credentials and no hub source. A+ hub-only gate could refuse entry to a working setup. C4 must state the mode handling and+ the degradation, and acceptance must cover both a fresh profile and the stateful one.+- **Shared-file integration.** i18n JSON and `Wizard.tsx` are touched by three lanes.+ Mitigation: frozen key namespaces, region ownership, per-screen stylesheets, rebase duty+ on the second merger.+- **Handoff correctness across tiers.** The snapshot reads live DOM class names owned by+ another lane; C3 makes those names a contract and `geometry.spec.ts` fails when they move.+- **Engine not installed on first run.** D3 reuses the approved automatic active-entry+ behavior. C6 requires authoritative support preflight before potentially installing paths,+ an admitted ensure-runtime phase for every mode, and separate native consent/mode adoption.+ Unsupported holds the normal flow with recovery/Back; a healthy running Hub stays usable.+ Helper `ok` alone cannot prove readiness.+- **Migration ownership and copy.** Owner D10 supersedes the handoff's preservation promises.+ Reuse existing complete-group confirmation and backend takeover/journal; setup must not+ accidentally become a second migration/retry owner or promise rollback. Preserve unrelated+ settings and consume confirmed receipts rather than inferring readiness from selection.+- **Controller not running.** D11: Hub reads are IPC-backed; a stopped application cannot+ satisfy them before bootstrap. D11's active provider-entry operation seeds/readbacks config+ before connection calls, avoiding legacy empty-Slack startup, then starts only a confirmed+ stopped controller and reads RPCs. No disabled-gateway branch needs bootstrap support. Runtime support checks must follow controller+ availability rather than converting an IPC failure to unsupported or ready.+- **Model-ranked routing.** No global route transaction exists. C6 defines exact targets,+ shared subset projection, divergent hydration, explicit catalog/hop repair and partial+ readback/retry. Existing chain writes have no CAS; concurrent external edits cannot be+ excluded. A shared reorder freezes only changed targets, preserving unrelated routes.++### 9.1 Review-loop record and current repair contract++The orchestrator inventoried all paginated threads at each round. Current totals: 25 findings+across eight findings-bearing review heads — `d9c62aa2eb` (2), `cf3b47e8cd` (4),+`5ea80ceeec` (4), `de9c324872` (4), `f177ead2c2` (4), `616a0b539d` (1), `890014421f` (1),+`08b82658bb` (5) — with 21 resolved and four open at this update. Counts use each finding's+original review commit. Review `5263295829` on published `08b82658bb` is terminal, and all 18+of that head's checks succeeded; a green CI run is not a review pass, so no pass is claimed.+This is orchestrator-provided inventory, not an executor GitHub read.++Diagnosis and scope decision. Two distinct roots produced the repeated lifecycle/capability+findings, and they need different treatments:++1. **A product-boundary scope error (rounds 6–7).** Review inferred a second setup journey+ from separately existing Settings/Direct capability. The owner resolved that boundary:+ setup uses Model Hub, and disabling it is a post-setup Settings action. Both the automatic+ unsupported-to-Direct fallback and the retained capability-off setup branch were retracted,+ along with the bootstrap expansion proposed for that excluded path. Normal Hub D11+ bootstrap, runtime support checks, healthy Hub access, error/retry/Back and drafts are+ unchanged.+2. **Invented browser ownership over existing server owners (round 8).** The contract had the+ browser preflight installation before a controller start that already performs its own+ recovery and server-side admission, gate non-installing engine writes with an+ install-admission predicate, read a cached CLI snapshot as presence evidence, and prescribe+ a literal color beside its own token rule. Each correction names the real owner instead of+ adding a mechanism: controller-owned startup recovery, an operation table separating+ installing from healthy-engine writes, the shipped CLI generation authority, and the shipped+ shadow token.++The published five-file Hub-contract correction was contractual and pure helper/test work.+This update is limited to three documentation/metadata files: no runtime architecture,+Settings/backend change, executable contract change or feature lane.++| Thread | Owner-ratified boundary / executable evidence |+| --- | --- |+| `PRRT_kwDOPbFPYs6kO76r` / `4059240601` | No Direct completion on unsupported hosts. Normal three-screen sequence and fresh Hub gates remain, with no unsupported installation; retry/Back/drafts and healthy existing Hub use are tested |+| `PRRT_kwDOPbFPYs6kPKSx` / `4059328091` | Disabled gateway is not a supported Direct setup branch. No provider skip or bootstrap expansion for it. Preserve disabled config, expose prerequisite/recovery, and leave post-setup Settings choices untouched; consumer verifies no install or completion |+| `PRRT_kwDOPbFPYs6kPhkJ` / `4059468857` | C4 now requires corroborated presence through the shipped generation authority (`createAgentCollectionReadAuthority.refresh()` → `refreshAgentPresence()` then a generation-controlled list read) after install/path change and before completion. Consumers prove install-then-refresh eligibility, post-refresh current read, superseded reconciliation, failure holding and the real two-call transport |+| `PRRT_kwDOPbFPYs6kPhkR` / `4059468865` | C6's operation table scopes install admission to operations that can ensure/install, and admits healthy-engine observe/create/OAuth/mode/chain writes under their own guards. A composed backend case proves a binding write restarts the existing verified binary with zero installer calls while an unchanged-binding write does not restart |+| `PRRT_kwDOPbFPYs6kPhkV` / `4059468870` | Owner-supplied handoff designates `avibe-docs/design_desktop.pen` and Show session `ses36vg559de2` for these setup frames; that task-specific source overrides the repository's general default. Recorded as known-by-design in the PR body; no canvas substitution, no design-file edit, native frame verification still required of the visual lanes |+| `PRRT_kwDOPbFPYs6kPhkZ` / `4059468875` | §4.8 and C3 name `var(--ob-active-shadow)` (backed by `--shadow-glow-onboarding-mint`) instead of a literal hex shadow; handoff hex values are design references, and a missing value becomes a token |+| `PRRT_kwDOPbFPYs6kPhkc` / `4059468880` | The observation was right and no new mechanism was added: C6/D11 now state that controller startup owns the first runtime recovery and server-side installer admission, the browser observes that outcome and requests admitted recovery only if the engine is still missing, and no second unconditional lifecycle call follows. Composed backend cases exercise the real `Controller._recover_runtime_owners()` → `recover_runtime_intent()` → adapter/supervisor/installer chain |++Repeated classes audited together: exact Agent/menu-model/pair identity and readback (D4/D9);+enabled prerequisite → active-provider persistence → controller recovery/server admission →+browser observation → operation-specific recovery/consent → readback (D3/D11); complete scan+groups and React functional state consumers (C2/C6); plan/type/copy and authority consistency+(C1–C6). Owner D10 now selects the existing migration feature; this update changes+plan/contracts/C1 metadata only, with unchanged C2 state and consuming tests.+Locale/plural/placeholder and scope checks cover these edits; unaffected executable-suite and+build evidence below is reused. The known-by-design ledger resolves only the named+product-boundary and design-provenance requests, not correctness/review/CI gates.++Round-8 evidence, independently rerun by the orchestrator against this worktree: five frontend+consumers of the real CLI generation authority and real `modelsApi` transport+(`agentPresence.test.ts`), and four composed backend cases driving the real controller recovery+chain with a test-owned artifact (`test_round8_recovery.py`) — unsupported host resolves no+archive and performs no install/start while other controller owners still complete, supported+default-on recovers exactly once, explicit disabled intent is preserved with zero lifecycle+calls, repeated RPC status reads never replay lifecycle, and a healthy engine's binding write+restarts the existing binary without installer admission. Both live outside the PR as design+proofs; L2/L3 must port them to their real owners. C1 parity (109 keys per locale),+`git diff --check` and file-scope checks pass. No feature E2E, deployed verification or visual+acceptance is claimed.++Provenance of this update: the delegated executor produced the four contract corrections and+both proofs, then its session failed twice at the model layer+(`model_hub_recovery_exhausted`) with local edits intact. The orchestrator verified the diff+and reran both proof suites itself, completed the remaining documentation, review record and+publication material, and published. Single-writer discipline held: the executor run was+terminal and its queue empty before the orchestrator edited.++Published Hub-contract correction evidence: ten `setupFlow.test.ts` tests passed, covering the+fixed journey, disabled prerequisite (deployment and saved intent separately), unsupported+no-install/no-Direct entry, independent healthy Hub use, retry/Back, drafts and late functional+state updates. Changed-file ESLint, dedicated consuming-test+TypeScript validation, UI build, C1 parity/plural/placeholder checks (109 keys per locale) and+`git diff --check` pass. These consumers use synthetic runtime/connection evidence; they do+not prove feature E2E or backend authentication. The ten external frontend transport tests+also passed after adding saved-intent config validation. Prior unaffected evidence follows;+automatic-fallback tests are superseded and no shared-branch bootstrap proof is claimed.++Prior bounded-repair validation: 73 focused Vitest tests passed (`setupFlow`,+`MigrationDialog`, `gatewayAdoption`, `RuntimeNotStartedAction`); three hermetic backend+takeover tests passed (global/project cleanup, shadowed-key protection, post-exposure+recovery). UI build, changed-file ESLint, a dedicated TypeScript check of the consuming test,+C1 validation (locale/plural/placeholder parity) and `git diff --check` passed.+These are not proof of screen-2 runtime orchestration or a completed route implementation.+The technical-closure pass passed 61 UI tests (`setupFlow`, `routeChainDraft`,+`RouteChainDialog`) and five existing Agent-model prefill tests, plus seven temporary+composed backend fixtures outside the PR scope: real config POST + control startup readiness, preservation of existing+config, and the five requested routing cases. Engine/process collaborators are synthetic;+this proves backend orchestration feasibility, not the frontend call chain, a shipped feature,+live inference or visual design. The bootstrap correction passed 10 separate temporary frontend tests with a+consumer of real ApiProvider/serializer/apiFetch to verify JSON/CSRF, uncached readback,+error handling and absent cache/convergence side effects. The two layers do not claim E2E.+L2/L3 must add consuming coverage with the actual feature owners. Current Hub-gate coverage+retains the original React state consumer. Orchestrator spot-checks the repaired diff and+a consuming test before delivery continues.++## 10. Decisions, provenance and remaining binding conditions++The owner explicitly reaffirmed Model Hub setup with disabling only in Settings afterward;+this supersedes both orchestrator interpretations of Direct setup compatibility. At 13:19 +08+the owner separately ratified D10's existing migration takeover and setup-consumer boundary.+These decisions do not approve all other technical/design choices. Existing product contracts+remain reusable evidence; routine technical choices belong to the orchestrator. The user's confirmation+before feature implementation and explicit authority before #2082 merge remain outstanding.++| ID | Provenance / current choice |+| --- | --- |+| D1 — #2065 | Owner-authorized merge, squash `31c4e831b`; no implied #2082 merge/feature authority |+| D2 — shared key form | Orchestrator decision: extract existing `AddApiKeyDialog` form into setup's stable frame; preserve Settings behavior/tests |+| D3 — runtime setup | Existing approved `model-hub-native-takeover.md` flow, adopted by orchestrator: automatically prepare runtime on active entry; active-provider config/bootstrap, C6 support preflight and admitted ensure/install/start/readback for all modes; unsupported recovery preserves the default Hub requirement and healthy running Hub. No enable/install-confirmation dialog and no automatic credential takeover |+| D4 — shared model route | Orchestrator-ratified bounded technical interpretation (not owner feature approval): one designated builtin setup Agent per installed/enabled backend, explicit named target if no builtin, exact saved menu model, shared order projected through each target's reviewed exact-hop membership. Preserve other menu-model routes, default and Agent models. C6 specifies hydration, repair and partial-write retry |+| D5 — setup prerequisite | Owner-ratified Hub-only setup; unsupported/error/disabled config never creates Direct completion. Disabling belongs to Settings afterward. C4 retains correlated Hub readiness and healthy Hub independent of installation; C2 preserves config, retry/guide/Back and drafts. Specific known-by-design resolution, no gate waiver |+| D6 — handoff §13 | Concise recommendations: destinations logo/name, reference English wording, capsule restoration, dashed Add-more. No native Pencil inspection or design-source synchronization claimed |+| D7 — vendor list | Orchestrator decision: shipped catalog/order, no prototype Cohere; no backend catalog change |+| D8 — copy scope | Orchestrator decision: setup copy scope separate from Settings, with takeover copy selected by owner D10. Minimal controlled-state/copy adaptation of the existing migration owner is future L2 work |+| D9 — row identity | Orchestrator-ratified technical interpretation with D4. Model-ranked `(source_id, model_id)` remains required. Unapproved source-ranking substitution withdrawn. Exact menu model vs upstream model, membership projection and successful manual-override readback specified with D4; no arbitrary Agent-model changes |+| D10 — migration ownership | **Owner-ratified 2026-09-21 13:19 +08:** reuse existing migration takeover. Setup owns discovery/entry/context and receipt-derived presentation; `MigrationDialog`/grouping, scan/apply APIs, `migration_apply`, `apply_native_migration` and journal retain confirmation, cleanup, custody/mode transition and recovery. Exact consequence + Not now / Start migration, API-key-only setup entry, mixed OAuth group blockers, unrelated settings preserved. Supersedes handoff copy-only/unchanged-connections/atomic-rollback promises; no separate setup migration mechanism |+| D11 — controller bootstrap | Orchestrator-ratified corrected sequence: active provider entry with enabled capability and saved runtime intent → CSRF-aware `apiFetch` POST `{}` with JSON Content-Type and HTTP/body validation → uncached GET parse installed in shell config state → successful connection read proving persisted config → confirmed stopped/start/readiness → Hub runtime sequence. `mutateConfig([])` rejects before transport; no change to that validator. Direct fetch has no ApiContext cache/convergence side effects. Unknown writes stay pending until existence is proved; GET defaults alone cannot prove persistence. Separate frontend transport and backend fixture evidence, not E2E |++D4/D9 fixture results: exact same-source model pairs persist distinctly; disjoint native+Claude/Codex subscriptions retain subsets; editing one builtin route leaves a custom Agent's+different model/route intact; fresh Agents receive server recommendations and OpenCode can+admit its exact saved menu id before explicit upstream-hop mapping; divergent chains are not+rewritten on open; a second target's failed write leaves the first confirmed and retry skips+it. The composed fixture contains the proposed projection coordinator and calls real service+primitives; it is not production L3 code. Existing primitive tests cover model prefill, exact+route guards and unknown-write readback independently.++D10 settles migration behavior and copy while retaining C2's full scan + backend-group draft+and functional setter as presentation/context state. L2 shares that state through the existing+feature's minimal controlled adaptation and consumes confirmed receipts; it does not own a+migration transaction or native credential material. No executable interface change is needed+for ratification. Merge #2082 and feature start remain separately gated.++## 11. Out of scope++Desktop shell loading page; Model Hub service semantics and any backend routing redesign;+production credential-scan behavior beyond reusing scan/apply; macOS menu bar and other+OS-layer work; IM platform configuration in onboarding (already moved to Settings —+`SetupPlatformRecovery` remains only as a recovery path); handoff §11's adjacent changes,+which landed through #2033/#2047/#2050/#2051/#2058/#2067/#2068/#2069 and are re-verified+here only where they touch setup.diff --git a/docs/plans/setup-three-screen/contracts.md b/docs/plans/setup-three-screen/contracts.mdnew file mode 100644index 000000000..41db1e4a0--- /dev/null+++ b/docs/plans/setup-three-screen/contracts.md@@ -0,0 +1,713 @@+# Setup three-screen — contracts C1–C6++Status: **PR0 interface proposal; D10 owner-ratified**, audited against head+`08b82658bbbf3e3e952fa1007c13f93fbca51410`. The handoff remains unchanged user source.+The approved `model-hub-native-takeover.md` supplies runtime/custody precedent; the+orchestrator adopts its automatic runtime preparation and the routine decisions in plan §10.+The owner reaffirmed on 2026-09-21 12:56 +08 that setup uses Model Hub; disabling it+belongs to Settings afterward. There is no Direct setup branch, including explicit opt-out.+At 13:19 +08 the owner ratified D10: setup delegates migration takeover to the existing+migration feature. C1/C6 supersede the handoff's copy-only, unchanged-connection and atomic-+rollback promises for this flow; they do not alter the source handoff.++C1–C6 now specify the selected custody behavior and concrete technical mappings. D4/D9 is+orchestrator-ratified as a bounded technical interpretation. D11 is also orchestrator-ratified+for its config transport boundary. C6 now distinguishes controller-owned startup recovery+from browser observation and conditional retry, with separate composed owner evidence. Product+ratification does not authorize feature dispatch or extend #2065 merge authority to #2082;+requested feature authorization and contracts-on-master remain gates. Current work is PR0+only. A lane reports gaps instead of inventing a parallel contract.++| Contract | Where it lives | Owner |+| --- | --- | --- |+| C1 copy | `docs/plans/setup-three-screen/copy-contract.json` | orchestrator |+| C2 flow interface | `ui/src/components/onboarding/setupFlow.ts` | orchestrator |+| C3 geometry and DOM hooks | this file §C3 | L1, consumed by L2/L3 |+| C4 entry gate | this file §C4 | L3 |+| C5 stable dialog frame | this file §C5 | L2 (add + import), L3 (route) |+| C6 data mapping | this file §C6 | L2 (providers), L3 (assistants) |++## C1 — copy++`copy-contract.json` is the whole statement: the leaves under `onboarding.flow`,+`onboarding.providers`, `onboarding.import`, `onboarding.setup` and `onboarding.route`,+plus the existing strings it changes or reuses (listed in the fixture metadata). It was validated+for zh/en key parity, complete `_one`/`_other` families on every `{{count}}` string, no+nested-before-literal key collision, and identical placeholder sets per key.++Copy ownership and current implementation constraints:++1. **PR0 adds no key to the bundles.** `keyCoverage.test.ts` reads the literal keys out of+ the app source, so a key lands with the component that uses it, in the lane that owns+ both. Namespaces are the ownership boundary: L1 takes `onboarding.flow.*` and the four+ changed `onboarding.welcome.*` / `onboarding.access.*` strings, L2 takes+ `onboarding.providers.*` and `onboarding.import.*`, and L3 takes the new+ `onboarding.setup.*` and `onboarding.route.*` leaves plus the two changed+ `onboarding.setup.title` / `.subtitle` headings. `_changed_existing` carries an `owner`+ per row, and that field — not this sentence — settles a dispute.+2. **Migration takeover wording is selected by owner D10 (2026-09-21 13:19 +08).**+ `_migration_copy` records the selected copy and behavior. It supersedes copy-only,+ unchanged-connection and atomic-rollback promises for this flow; the source handoff stays+ unchanged. The existing migration feature presents the exact approved Chinese consequence+ and **Not now / Start migration**; only its explicit confirmation applies credentials.+ Setup supplies discovery/selection context and consumes confirmed results. Its copy scope+ and controlled selection need a minimal adaptation of `MigrationDialog`, not a separate+ migration coordinator. Settings keeps its existing rendering and broader migration scope.+ Counts describe migration items; an `applied` receipt alone does not establish readiness.+3. **The plural-family rule is local to the new keys.** 66 existing `{{count}}` strings+ outside `settings.models` ship without families, so a bundle-wide redline would fail+ today; this round holds the new keys to it instead of retrofitting the app.++## C2 — flow interface++`setupFlow.ts` declares the screen ids, the handoff target, the action feed+(`SetupAction`), the imperative handle (`SetupScreenHandle.activate`), the screen props+and the shell-owned `SetupFlowState`.++- The shell passes `flowState` and its React `setFlowState` setter to every screen.+ Consumers use `setFlowState(previous => ({ ...previous, changedField }))`, including+ asynchronous completions. Replacing captured state loses other screens' intervening work.+ `providerSelection` holds the complete ephemeral `MigrationScan` and selected backend+ consent groups shared with the existing migration owner, not an apply/recovery journal;+ `routeOrder` holds `(source_id, model_id)` rows, never source IDs alone.+ Neither is a second source of truth for persisted readiness.+- The shell renders the single primary and Back actions. Each `onActionChange` and+ `onNavigate` callback is bound to the emitting screen and activation; the shell rejects+ inactive/stale publications and clicks only the current `SetupScreenHandle.activate()`.+ Clear the previous action on navigation; disable it during capability reads, handoffs,+ and pending mutations. `busy` also disables clicking. `activate()` must reject re-entry.+- All registered screens remain mounted, `hidden` + `inert` when inactive. This preserves+ drafts but does NOT suspend effects. Screens gate polling, authorization, scans and+ animations on `active` (and dialog open state). A hidden screen must not start installs,+ mode changes or other mutations. Already-started operations retain one owner; their+ completion may reconcile state with functional updates, but cannot navigate, steal focus+ or publish the active action. Ignore stale read completions using an activation/request+ generation, not unmount cleanup alone. Leaving and returning never replays a mutation.+- Server facts (CLI presence, backend enablement, sources and routes) are re-read on active+ entry and after mutations. C4/C6 require the existing Agent collection authority to deep-refresh+ cached CLI presence after install/path/config changes and before completion; ordinary list+ reads alone cannot establish that freshness. Preserve unconfirmed drafts across those reads; C6 defines scan+ reconciliation, route targets and preservation of dirty target baselines. `setupFlow.test.ts` consumes the actual+ props with React state and checks navigation plus a late update, not just initial values.++`setupCapability(boolean | null)` maps the shell's validated config capability boolean to+`pending | enabled | disabled`. Validate `capabilities.model_hub.enabled` before using+`modelHubEnabledFromConfig`; missing data and request errors are pending, never disabled.+`useModelHubCapability()` collapses failure to false and is not a safe producer here.+`setupNavigationReady(capability,gatewayEnabled)` requires enabled deployment capability+and fresh saved `model_hub.enabled === true`. Missing/malformed saved intent stays null,+not implicitly true; these are separate config fields. Initial config+loading stays read-only; entering active providers starts D11, never merely mounting intro.++**Setup has one fixed sequence, `SETUP_SCREENS`: intro → providers → assistants.** Capability,+installation support and errors never remove providers or create a Direct branch. Back uses+`setupBackTarget(SETUP_SCREENS,current)` and keeps drafts. Host support is learned after+D11 bootstrap on active provider entry; controller recovery already enforces server admission+before the browser can read support. Do not require an RPC before reaching its bootstrap path.+Unsupported/error holds the current step. Clear obsolete action publications on navigation;+only the active owner may retry, claim the CTA or navigate.++An authoritative disabled deployment capability **or saved runtime intent** fails setup's Hub prerequisite. Show+`onboarding.flow.gatewayRequired`, the current configuration/recovery boundary and Retry;+keep the current step and Back if applicable. Retry re-reads config first; while capability+or saved runtime intent remains disabled/unknown, do not seed config, start a controller, call Hub RPCs, install, switch mode+or complete. The user must restore the existing configuration through its existing management+owner before resuming. There is no new setup toggle or implied Settings route exemption:+`ModelHubCapabilityGate` redirects when disabled and `App.tsx` restricts incomplete setup+navigation. Preserve those boundaries rather than linking to a recovery page that cannot+be entered. Completed instances' post-setup Settings choices remain outside this contract;+manual setup re-entry cannot silently re-enable or reset them.++The shell passes **`capability`, `gatewayEnabled: boolean | null` and+`runtimeRead: RegionRead<RuntimeDependency>`** through+`SetupScreenProps`, plus `onRetrySetup` for its existing config/bootstrap/runtime owner.+The retry first re-reads config; pending/error config reads hold capability pending, and only+fresh enabled capability and saved intent may resume bootstrap/runtime work. This+reuses the shipped read shape without a parallel setup policy/state machine. `readyRegion`+requires a successful validated response; null/malformed/HTTP/transport errors remain+loading/unread. `beginRegionRead`/`failRegionRead` retain old display data while refreshing or+failed, not authorization. Ignore stale request/activation completions. No hidden screen+starts a retry, installation or other mutation.++Three small predicates define distinct necessary conditions, not complete readiness:++- `setupCanAttemptInstall(capability,gatewayEnabled,runtimeRead)` requires enabled capability, a fresh read+ and `runtimeCanAttemptInstall`, plus saved enabled intent. Manifest `unsupported` blocks installation; `unresolved`+ is admitted. Neither browser platform guesses nor a 5xx determines host support.+- `setupHubRunning(runtimeRead)` requires fresh `ok`/`degraded` health independently of+ installation admission. Provider Continue requires this plus its action-specific guards;+ an existing healthy Hub remains usable on an install-unsupported host.+- `setupCandidateAllowed(capability,gatewayEnabled,runtimeRead,mode)` admits only persisted Hub candidates+ with a running runtime and enabled capability. Direct never passes setup, even with valid+ native credentials. C4 still requires the same candidate's actual route/auth/application/+ permission evidence.+ No helper changes mode, custody or the selected Agent.++A fresh runtime payload with `enabled === false` also blocks these gates even if an older+config read said true. Its optional field may be absent on older payloads, so fresh validated+config remains required. `runtime_start` writes saved `enabled = true`; therefore configuration+recheck must precede any browser-requested ensure/start, not just installation. Controller+startup independently re-reads persisted intent through its existing recovery owner (C6). Never turn a deliberate+stop into a start while recovering setup.++Unsupported/non-running holds Continue and completion on the same flow with C1's truthful+unsupported notice, **Recheck/Retry** (`common.retry`) and **View installation guide**+(`onboarding.providers.gatewayEnvironmentHelp`). The guide action opens the existing+[installation guide](https://github.com/avibe-bot/avibe/blob/master/docs/INSTALL_FOR_AI.md)+(Chinese counterpart `INSTALL_FOR_AI_ZH.md`), explaining how to use a supported environment;+it does not migrate this instance, promise platform availability or offer a Direct bypass.+The runtime response remains authoritative about current installation support. Network/read+errors show the existing runtime-unread copy with retry, not the unsupported notice.++The active owner may publish Retry as the shared CTA while Continue is held; do not apply+Continue's readiness gate to Retry or Back. Retry re-reads first, holds writes while pending,+then resumes the same flow on fresh support/running evidence. If support becomes admitted+but the runtime is stopped/missing, resume C6's automatic ensure path and read back running+health before continuing. Repeated unsupported responses keep the guidance and require an+explicit recheck; no automatic impossible-install loop. A later failure on assistants keeps+that screen's drafts and recovery/Back action. A running Hub needs no install to continue.++## C3 — geometry and DOM hooks++**Task-specific design provenance.** The owner-supplied handoff §12 selects+`../avibe-docs/design_desktop.pen` and Show session `ses36vg559de2` for these setup frames.+That task-specific direction overrides the repository AGENTS default `design.pen` for this+work only. Do not replace/copy either canvas or change the repository-wide rule. The handoff+remains immutable. PR0 has not inspected native Pencil frames: L1–L3 must inspect/export the+named frames and verify their token/geometry mapping before UI implementation and fidelity+claims. Source literals are reference measurements, not CSS prescriptions.++**Anchor pair.** One `.onboarding-setup-footer` rendered by the shell, containing one+`.onboarding-action-w.onboarding-primary-action` and, below it, one+`.onboarding-action-w.onboarding-back-action`. Their boxes are identical on every screen,+in both languages, at every viewport; `geometry.spec.ts` already asserts that across two+screens and L1 extends the same assertion to three. The Back button keeps its box on+screen 1 by staying invisible (`visibility: hidden`), which is how the reference holds the+anchor without a layout shift.++**Shared reservation.** `.onboarding-stage` remains the box both the story and the screens+below it occupy, so the anchor's vertical position does not depend on what a screen draws.+The import capsule lives in a reserved slot inside screen 2's stage: dismissing it leaves+the slot, so the primary action cannot move (handoff §4, and the assertion #2065 already+writes for the two-step flow).++**Snapshot hooks.** The handoff reads live DOM across screens, so these class names are a+contract, not styling. L1's `setupHandoff.ts` queries them; L2 and L3 must render them.+An inactive `hidden` root has no measurable box. L1 must temporarily lay out the incoming+root invisibly and inertly for measurement, without activating its effects or action feed,+then switch activity at handoff completion. Restore `hidden` after cancellation; the settled+state still has exactly one active screen. L1's geometry test must exercise this real path,+not measurements taken with every screen already visible.++| Transition | Reads from | Lands on |+| --- | --- | --- |+| intro → providers | `.onboarding-collaboration-card`, with `.onboarding-card-logo` and `.onboarding-card-name` inside it | `.setup-destination`, with `.setup-destination-logo` and `.setup-destination-name` |+| providers → assistants | `.setup-destination` and its two children, plus the retiring `.setup-provider-stage` | `.onboarding-assistant`, with `.onboarding-card-logo` and `.onboarding-card-name` |++Screen 2's own roots, in the same order the stage draws them: `.setup-provider-stage`,+`.setup-provider-grid`, `.setup-provider-card` (`data-provider` = vendor id, `aria-pressed`+when selectable), `.setup-wires--inbound`, `.setup-gateway`, `.setup-wires--outbound`,+`.setup-destinations`. Screen 3 keeps `.onboarding-assistants`, `.onboarding-assistant`,+`.onboarding-card-identity`, `.onboarding-assistant-state`, `.onboarding-assistant-body`.++**Tiers.** `onboarding.css` expresses the four desktop readings and the phone band as+`--ob-*` custom properties on `.onboarding-shell` under a fixed set of media queries+(`max-height:800`, `min-height:1001`, `min-width:1600 and min-height:950`,+`max-width:1023`, `max-width:759`, `prefers-reduced-motion`). L1 owns that file and adds+the tier variables screens 2 and 3 need from handoff §9. A screen stylesheet+(`onboarding-providers.css`, `onboarding-assistants.css`) consumes `--ob-*`, may restate a+value inside the SAME bands scoped to its own root, and may not invent a new band. No new+literal colors anywhere: values come from the `index.css` token scale or from `--ob-*`, and+`validate:theme` / `glowScale.test.mjs` keep that true. Active/hover card shadow uses+`var(--ob-active-shadow)`, already backed by `--shadow-glow-onboarding-mint`; its theme-specific+values stay in the shared tokens. Hover has no translate or scale.++**Motion bail-out.** Under `prefers-reduced-motion`, a hidden page, or an explicit pause the+handoff is skipped and the screen changes instantly; on phones the view scrolls to top+before the change. The primary action stays disabled and unmoved for the whole transition.++## C4 — entry gate++L3 owns the code; this is the semantics it must implement, and the semantics+`WizardCompletion.test.tsx` is re-pinned to.++**One assistant must satisfy the whole gate.** Three independent existential checks can be+met by three unrelated objects — an enabled Codex with no route, a persisted route on an+uninstalled Claude, a healthy source that neither route uses — and setup would then complete+on a machine whose first workspace turn cannot run. The gate is therefore correlated over a+single assistant, and it reads the server rather than any client-side draft.++With Model Hub capability and saved runtime intent enabled (the setup prerequisite), L3+builds the available set from fresh+`listVibeAgents({ cache: false })`: enabled, non-archived named Agents, joined by **backend+and Agent name** to backend connection/CLI reads and `AgentSupply.named_agents`.++| Condition for the same candidate | Authoritative read / rule |+| --- | --- |+| installed and backend enabled | `api.detectCli(cli_path)`, freshly corroborated `AgentSupply.cli_present` through `createAgentCollectionReadAuthority.refresh()` and `getBackendConnection(backend).enabled`; stale/failed refresh or read cannot prove readiness |+| Hub runtime running | `getRuntimeStatus()` with health `ok` or `degraded`; mode alone is not runtime readiness |+| model and route runnable | backend mode `hub`; that candidate's `named_agents` row has nonempty `effective_model_id`, `supply_status` in `ok` / `degraded`, and no `route_unconfigured` reason. `waiting`, `interrupted`, null or absent rows do not pass |+| application and custody | `getBackendConnection.ready === true` (including permission and matching credential ownership) and `application === 'applied'` are required alongside this candidate's route. Confirmed `stopped` permits bootstrap/recovery, never workspace readiness; draining/failed/unknown cannot enable entry |++Do not read backend-level `selected_model_id` to reject a different candidate: it describes+only `selected_by_agent`. The runnable-hop owner is the server resolver; neither an unrelated+healthy source nor a client `routeOrder` proves readiness. Revalidate on the completion click.++**CLI freshness owner.** `Controller` caches CLI presence; an ordinary `listAgents()` cannot+refresh it after installation. Use one shared `createAgentCollectionReadAuthority(modelsApi)`+for all setup supply reads. On active assistant entry, after install/CLI-path/agent-config+changes, and before corroborating completion, await `refresh()`: it calls+`refreshAgentPresence()` (`?refresh_cli_presence=1`) then a generation-controlled list read.+Consume only its `{kind: 'current', value}` result, not the raw refresh endpoint payload.+A concurrent newer generation can supersede that list read; hold completion and use the+same authority's current reconciliation/retry result. Failed or stale results retain display+only and keep Retry reachable. Invalidate superseded reads when a relevant mutation starts;+CLI detection success alone cannot release the gate. Re-read connection/config and join fresh+named-Agent supply by backend/name; this presence refresh is not authentication or route proof.++D11 establishes config persistence and controller availability on active provider entry+**before** Hub-dependent screen-2 work (C6). Enabled capability is a prerequisite; no bootstrap+expansion is needed for an excluded Direct branch.+`ModelHubRemoteService` uses the controller socket; `engine_down` on a missing socket is+neither an unsupported manifest nor proof of a bad model route. If the controller stops+later, retain a reachable start/retry action using confirmed application `stopped`, bootstrap+it, let controller-owned recovery run, and re-read runtime, connection and candidate supply+before allowing completion. Reuse recovered health; do not send a second unconditional+ensure/start. Startup+has no assistant/source readiness prerequisite. Do not restart after an enable/config write.++Preserve `default_agent_name` if it remains in the available set, including a usable custom+Agent outside the route editor's setup targets. Otherwise prefer a runnable setup target in+C6's stable order, then an available named Agent in stable backend/name order; call+`setDefaultVibeAgent` and verify a fresh Agent read. Write `setup_completed` last through+`api.mutateConfig` with an explicit field mutation, then validate a fresh uncached+`apiFetch('/api/config', {cache:'no-store'})` readback before navigating. Use that same+read/parse path after an unknown/failed write; cached pre-write data cannot settle it.+Unknown writes are reconciled by reads, not treated as success or blindly retried. Keep `SetupPlatformRecovery` for+existing invalid IM configuration. `SetupModelRecovery` is the shipped **Direct OpenCode**+recovery; it does not repair Hub models. C6 specifies Hub catalog/chain repair.++The new Hub route predicate replaces credential readiness / `entry_eligible` as the *route*+criterion, not the confirmed application-state or backend permission guard. Today's `Wizard.complete()` only+filters OpenCode routes; the all-backend named-Agent join is new L3 orchestration, not a+helper that already exists. Unrouted enabled assistants retain a configuration action (C6).++**Known by design — setup requires Model Hub.** Owner decision, 2026-09-21 12:56 +08:+“setup的契约是默认使用模型网关”; users who later need to disable it do so in Settings.+Unsupported installation without a usable running Hub cannot complete setup, even with+working Direct credentials. Explicitly disabled gateway configuration also does not create+a Direct setup branch: preserve that saved choice and expose the C2 configuration/recovery+boundary. No silent enabling, custody rewrite or setup-completion write bypasses it.+A fresh healthy Hub still uses the correlated gate above regardless of install admission.++This is the intentional non-change for `PRRT_kwDOPbFPYs6kO76r` / `4059240601` and+`PRRT_kwDOPbFPYs6kPKSx` / `4059328091`: neither unsupported-host Direct fallback nor a bootstrap+expansion for disabled-gateway setup belongs to the product journey. D11 still supports the+normal Hub setup. Existing Settings/backend Direct support and completed-instance preferences+remain untouched. This specific owner-ratified boundary is **not a Codex gate waiver**:+unavailable retry/Back, unsafe installation, lost drafts and false readiness in the normal+Hub flow remain defects. Current-head review, unresolved-thread and CI gates still apply.++## C5 — stable dialog frame++Applies to all three screen-2 dialogs and to screen 3's route dialog.++- One frame per dialog across every tab and state: 568 wide, 24 padding, 16 radius, 20+ gaps, and a common height taken from that dialog's longer ordinary form (not from an+ unusually long error), bounded by the viewport.+- Anchored: title, description, method tabs, close control, action footer. Scrolling: the+ middle region only — long errors, provider lists and authorization notes scroll inside+ it, and every action stays reachable at browser zoom and on a short screen.+- Loading, tab switching, authorization progress and error all reuse the same frame; a tab+ switch preserves drafts and focus. A hidden pane keeps no focusable control and starts no+ duplicate authorization effect.+- Focus returns to the element that opened the dialog; Escape and an outside click close it,+ except that the import dialog is not closable while a batch is applying.+- Phones: the frame accounts for the keyboard and the safe area. No single absolute height+ is applied app-wide.+- Acceptance is the repeated-switch test at one viewport — heading, tabs, frame and footer+ do not move while the middle scrolls — not a height transition.++## C6 — data mapping++Field names are exact. Every row names its producer and its consumer, because a shape-only+contract passes both sides' unit tests while the behavior silently disagrees.++Each row distinguishes a shipped owner from required setup orchestration. Reuse an owner+where its actual inputs and outputs fit; controlled state, support preflight and shared model+mapping cannot be attributed to helpers that lack them. A lane reports contradictions instead+of silently changing either the handoff or another owner.++### Screen 2 — providers++| Element | Producer → consumer and rule |+| --- | --- |+| scan and discovery | existing migration feature `modelsApi.scanMigration().items` → full `providerSelection.scan`; `isImportableKey` identifies entry-point keys only. Keep every row; reuse its group closure/blockers before the actionable capsule count; a blocked detected key remains visible with its reason but is not advertised as importable |+| candidate identity | `MigrationItem.id` is selection identity, never vendor alone. Use `providerLabel` / `providerVendorId` as `MigrationDialog.ItemRow` does. Optional vendor/name/mask may be absent: generic mark plus `masked_detail`, never infer vendor from backend or fabricate a mask. Show every `source_paths` locator; only when absent use `migration.source.<backend>`. `notes_key` is an explanation, not origin |+| cards | slots 1–2 show detected/provider identities then existing sources, with OpenAI/Anthropic placeholders if needed; slot 3 is Add more. Vendor grouping is presentation only: multiple keys from one vendor retain separate IDs and may require whole backend selection |+| selected and connected | selected means complete consent group selected; a blocked group is disabled with its reason. Added/connected treatment follows confirmed source IDs from `listSources` and status `active` / `standby`; `verification_pending` is disclosed as unverified, not rejected as unusable (the shipped resolver accepts standby). One vendor's healthy source does not prove every key/card connected or a runnable assistant |+| counts | CTA count = deduplicated appliable item IDs in selected complete groups; summary provider count = distinct displayed providers of those items. Capsule count = distinct key IDs in complete, unblocked, key-only groups, independent of selection. `importedCount` = confirmed `result.applied`, once per successful submitted batch, not number of sources or guessed key count. `addedThroughMore` = unique IDs returned by successful manual creation, badge filtered against current usable sources |+| capsule | retain dismissal signature owner `modelHubMigrationDismiss` and the reserved slot. Existing `ImportKeysNotice` scans/owns a dialog internally: L2 must adapt it to the shared scan/selection owner before claiming consistency; it is not a drop-in consumer of C2 |+| import / Detected tab | use the complete-group rule below. Hiding card duplicates or out-of-scope rows must never shrink consent. Already-added status follows fresh scan/source evidence, not a vendor-name match. D10 delegates confirmation/apply/recovery to the existing migration feature; setup never applies from selection or normal navigation |+| add — API key | shared `AddApiKeyDialog` form: observe then create with the confirmed observation, preserve its existing unknown-write recovery. Read `SourceCreated.source` and placement tails (`added_to`, `adopted_by`); refresh sources and affected supplies before reporting ready |+| add — subscription | reuse `subscriptionOptions.ts` / `OAuthConnectDialog` / `OAuthFlowParts` for the offered product vendors, custody choice and flow ownership. Setup limits the shipped vendor list to OpenAI/Anthropic per handoff; there is no callable vendor-capability-list API in `ModelsApi`, and no such producer should be invented. `getOAuthStatus` / `submitOAuth` return `OAuthResult`; terminal create carries `created.source` and placement tails. Do not create the source a second time or equate terminal OAuth with assistant readiness |+| picker order | `apiKeyVendors.ts` reads `vibe/data/api_key_vendors.json`; first eight in file order, remainder plus custom. No browser re-sort or prototype Cohere |+| runtime | with enabled capability and saved intent, D11 starts only a confirmed stopped controller; its existing recovery owns initial ensure/start and server admission. The browser then observes health and only requests admitted recovery if still needed (D3). Healthy-engine writes follow the operation table below, independently of new-install permission. Unsupported/non-running or unread stays on the normal flow with retry/guide/Back; no install-confirmation or automatic credential takeover |+| first entry | cards → inbound wires → gateway → outbound wires → destinations, about 1.1s; C3 bail-outs; no production reset/replay control |++#### Complete consent groups (current thread `PRRT_kwDOPbFPYs6kOVg6`)++The shipped owner is `MigrationDialog.tsx`: `eligible` scopes entry-point **backends**; it+does not filter the scan before grouping. Starting at those backends, repeatedly union+`required_backends` from **every row** of every included backend until stable. Missing/empty+metadata means that backend alone. Retain every row of the resulting closure, including+OAuth, `reauth`, `keep_native`, non-key rows and blockers, and display required backend/file+impact. A non-`import` row blocks its entire linked group. Toggling any member selects or+deselects the full linked import group; never submit a partial backend.++C2 stores `{ scan: MigrationScan | null, selectedBackends: AgentBackend[] }`, where the+backend list is the union of complete unblocked groups. The adapted migration owner derives+apply IDs from the **same scan**: all `proposed_action === 'import'` rows whose backend is+selected, once per ID, and validates closure/blockers again before its confirmed apply. With+setup's API-key-only requirement, an otherwise importable OAuth member also blocks the group+for this entry point; show it and explain that the full migration is available in Settings.+Never silently import OAuth or drop it from a batch.++L2 makes the smallest controlled-state/copy adaptation of the existing dialog/grouping+owner so discovery cards, capsule and Detected tab consume that same feature. Current+`MigrationDialog` has only `open/onClose/onApplied/eligible` props and local `items` selection;+the shared state/copy inputs and setup key-only whole-group constraint are future adaptation+work, not already shipped props. Keep one grouping/confirmation/apply/recovery owner: no+independent item-ID selection engine, setup-specific migration coordinator or retry engine.+Rescans invalidate old item IDs: preserve selection only for unchanged complete groups;+changed membership/custody requires renewed review, and failed rescans disable apply rather+than submitting stale IDs. Default-selection applies only to fully importable, unblocked+initial groups, respecting the server's `selected` flags.++The migration owner publishes confirmed results; setup clears confirmed group selection,+increments the receipt-derived batch count once, then refreshes scan, sources and supplies.+`applied` counts migration items, not assistant readiness. Today's `onApplied(number)` carries+a count only, and `onApplied(0)` is also called for `migration_credentials_invalid` to refresh+the caller. Treat zero as refresh-only, not proof of completed takeover; preserve the owner's+error/recovery UI. Any receipt distinction needed by setup belongs in the same small owner+adaptation, not guessed from local selection. Unknown transport outcomes remain with that+feature's reconciliation/recovery; the server journal and same item IDs can resume/replay the+operation. Setup neither retries apply itself nor fabricates a rollback or partial success.++#### Migration takeover — D10 (owner-ratified 2026-09-21 13:19 +08)++Owner decision: “setup只负责默认使用模型网关,不负责迁移,采用 迁移接管 实现”. Setup owns the+Hub journey, discovery/entry presentation, assistant readiness and receipt-derived display+state. The existing migration feature retains migration behavior through this call chain:++`MigrationDialog` / shared grouping → `modelsApi.scanMigration` / `applyMigration` →+service `migration_scan` / `migration_apply` → `apply_native_migration` and its journal.++The backend owner provisions sources, removes replaced native credentials/direct-routing+fields, commits Hub mode/placement, and owns transaction/recovery. Tests prove global/project+key cleanup, preservation of unrelated MCP/name settings, and retained custody for recovery+after exposure. Setup must not duplicate cleanup, custody writes, mode transition, rollback+or retry machinery, and must not send a second mode PATCH after successful apply.++Cards, capsule and Detected actions delegate to this feature's complete-group review. Keep+every required backend/file visible and show the exact consequence+`迁移后,CLI的认证信息将完全交由模型网关管理`, with **Not now / Start migration**. Only the latter+explicit confirmation invokes apply. New/incomplete takeover invokes server dependency ensure+before credential withdrawal and again before sync/start; it retains installation admission+even when a healthy engine exists (operation table below). Selection, setup entry, gateway installation/start and+normal navigation are never consent. Not now leaves native authentication and mode unchanged.+Setup's entry remains API-key-only: mixed OAuth or non-importable groups are blocked as a+whole, with the broader migration feature remaining in Settings. Unrelated settings stay+preserved; source/assistant readiness is re-read after the feature's confirmed result.++This selected behavior expressly supersedes the handoff's copy-only, unchanged-assistant-+connections and atomic-rollback promises for this flow. Success reports the migration owner's+completed takeover/cleanup; failure or unknown outcome requires its reconciliation/recovery,+which can retain changed credential custody. C1's selected copy describes those consequences.+No credential-copy alternative or new native-coexistence design is part of the implementation.+The original handoff remains immutable, and D10 adoption is not permission to migrate real+credentials during PR0 or to start feature lanes.++#### Controller bootstrap — D11 (orchestrator-ratified technical sequence)++L1's existing setup shell owns one bootstrap operation on active provider entry with enabled+capability and saved runtime intent, before Hub RPCs. A hidden screen cannot start it. If a fresh config read reports+either capability or saved intent disabled/unknown, stop at C2's prerequisite boundary without changing that preference.+**Do not call `api.mutateConfig([])`:**+`configMutationsToPayload` rejects empty mutations before any HTTP request. Keep that general+validation intact. The smallest setup-only composition uses the existing CSRF-aware+`apiFetch` directly; no new API service or production helper is introduced by PR0:++```ts+const response = await apiFetch('/api/config', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+});+// Validate HTTP status and parse the POST body as described below before proceeding.+const readback = await apiFetch('/api/config', { cache: 'no-store' });+// Validate HTTP status and parse the fresh GET body independently.+```++`apiFetch` supplies Accept/CSRF and its existing remote-auth handling. It returns a Response;+it does not validate HTTP success or the body for the caller. POST and GET success return a+**top-level config object**, not `{ok:true,config:...}`. Validate a JSON object with no error+or `ok:false`, `version === 'v2'`, boolean `setup_completed` and+`capabilities.model_hub.enabled` and saved `model_hub.enabled`, string `platforms.primary`, string-array+`platforms.enabled`, and object `runtime`/`agents` before consuming these fields. Preserve+load-recovery warnings for the existing recovery path. An absent/malformed required field+is unread state, not an explicit capability opt-out.++A non-2xx POST or explicit error body is not success: retain HTTP status and server error+(string or structured object) for the active owner's error UI. A definitive refusal blocks+startup. A transport failure, invalid/truncated 2xx body or server 5xx has an unknown write+outcome; do not blindly repeat POST. Both acknowledged success and unknown outcome take the+same uncached GET/JSON validation path above (a failed read stays blocked). Error responses+may also be read back for diagnosis, but that read never clears a definitive refusal.+Crucially, GET serves an **in-memory default when no config file exists**. Therefore a valid+GET alone cannot settle unknown persistence: subsequently require a successful+`getBackendConnection` response (`ok:true`, valid application state), whose server owner+calls `load_config()`. If it fails or remains unknown, keep bootstrap pending/recoverable;+never let `control('start')` fall back to creating the legacy config. Once that read proves+config existence, the empty patch's only intended effect is reconciled; a later explicit+retry can reseed an actually absent config without overwriting user fields.++A direct `apiFetch` POST **does not clear ApiContext's 30-second config cache or emit+`onConfigChanged`/configuration convergence**. L1 explicitly installs the validated fresh+GET into the shell's existing server-config state (`data` in today's Wizard), scoped to the+current request/activation. Feed capability, platform recovery and bootstrap decisions from+that snapshot. Future authoritative setup reads use the same direct uncached read/parse+path, including unknown-write reconciliation; do not replace it with cached `api.getConfig()`+or assume a global notification occurred. C2's draft state/setter remains unchanged.++The server empty patch seeds missing config through+`core.services.settings.default_config()` and lock-merges existing state, preserving+`setup_completed`, platforms and other user choices. It must precede connection reads,+which require a config file. `runtime.ensure_config()` alone still seeds legacy Slack+defaults; the settings API seeds workbench-only defaults (`platforms.enabled=[]`, primary+`avibe`, setup incomplete). No stale full-config round trip or reset is needed.++After verified config, a fresh connection with confirmed `application === 'stopped'` permits+`control('start')` from `useStatus`; an applied controller is reused. Draining/failed/unknown+uses existing recovery/read paths, never an inferred restart. The control consumer checks+its HTTP rejection and returned body `ok === true`/`action === 'start'`, then re-reads backend+application and controller RPC availability. Controller startup itself calls+`_recover_runtime_owners()` → real `ModelHubService.recover_runtime_intent()` →+`_prepare_engine_for_demand()` → adapter ensure and start for saved enabled intent. This can+install/start Hub before the browser's first runtime RPC; the browser does not own or precede+that recovery. `EngineRuntimeManager` / `ManagedRuntimeManager.ensure` resolves host archive+admission before fetching/installing runtime assets. Unsupported rejects there; optional Hub+recovery failure is caught by Controller, which continues other owners and retains blocked+Hub readiness. Manifest lookup may occur; no claim of zero filesystem bookkeeping or network+manifest resolution is made. Disabled intent is not enabled by recovery; previously confirmed+migration journals and orphan install claims retain their existing recovery owners.++After controller readiness, read the recovery outcome. A fresh healthy Hub needs no browser+ensure/start/restart. If recovery failed or health remains stopped/missing, C6 below governs+an explicit/active recovery attempt using fresh config and runtime evidence. A `down` status+can be the service's projection of failed demand, not proof of installed bytes. StatusProvider's+`refreshStatus()` only refreshes service status and may return null; neither it nor a cached+status alone proves config persistence or backend readiness. Missing CLI, sources, routes+and incomplete setup do not forbid controller startup. Bad existing platform configuration+uses `SetupPlatformRecovery`; do not disable configured transports or restart after an+already-reconciled config write.++Evidence is separated deliberately. The temporary frontend consumer imports the **actual+ApiProvider, serializer and apiFetch** with mocked HTTP: empty mutations reject before POST;+setup POST sends `{}` with JSON/CSRF; fresh GET bypasses both the primed ApiProvider cache and+HTTP cache; direct POST leaves cached config and convergence subscribers untouched; refusal,+unknown POST and invalid GET stay distinguishable. Separate hermetic backend fixtures drive+real config POST/GET, persistence and connection/control handlers with a fake process launch+and the existing real-loop readiness harness. They prove fresh seed, existing-state+preservation and control-handler startup without sources or completed setup; their fake+process did not prove actual Controller runtime recovery. Round-8 external composed tests+separately invoke the real Controller recovery method, service, adapter, installer and+supervisor with test-owned archives/storage and synthetic process/health peers: unsupported+refuses artifact installation/start while other owners recover, supported default-on restores,+disabled intent stays disabled, and later status reads do not repeat completed recovery.+`runtime_status` can reconcile an orphan installation claim through the existing owner; it+is not universally side-effect-free. These are separate transport/server/composed proofs,+**not browser/server E2E**, full Controller construction or a shipped setup implementation.++#### Observe recovered runtime, then prepare adoption++0. D11 establishes controller availability; server-owned auto-recovery has already attempted+ saved intent with installer admission. A missing socket/read error is not an unsupported+ manifest. Preserve pending/error and Retry/Back; do not manufacture readiness.+1. The active owner obtains fresh config intent and `getRuntimeStatus()`. If health is already+ `ok`/`degraded`, reuse it regardless of manifest install admission. Ordinary source/route/+ OAuth/mode work follows the table below and each existing owner's health, custody and+ consent guards. Completion still uses C4; unsupported never creates Direct setup.+2. If engine recovery is still needed, require `setupCanAttemptInstall` / authoritative+ `runtimeCanAttemptInstall` before browser ensure/install/start or helpers that may invoke+ them. `unresolved` is admitted; unsupported and failed/stale reads are not. With admitted+ support and saved enabled intent, `resumeInstallAndStartRuntime` resumes the needed phases+ for any backend mode, including already-Hub stopped/missing. Observe `onRuntime`, handle+ `failedStep`, then read back health. `installAndStartStep` only classifies;+ `installRuntimeUntilSettled` does not start. None of these helpers preflights support.+ No second unconditional lifecycle call follows successful controller recovery. Unsupported+ without running health holds the normal flow with recheck/guide/Back and intact drafts.+3. `resumeGatewayAdoption` is not a readiness/consent owner: it returns early for Hub with+ `runtime: null`, otherwise can ensure/start and returns backend-filtered candidates; it+ never changes mode/applies migration or checks support. Do not wrap healthy-engine actions+ in it just to impose an install gate. Reuse observed health and delegate full-scan consent+ to the D10 migration owner. If used for recovery, it needs the installing-path gate.+4. For a ready runtime, native rows delegate to existing complete-group review and explicit+ migration apply, with its actual ensure dependency; no native rows use the guarded+ `setAgentMode(backend, 'hub')` path without an extra confirmation/install gate. Migration+ already commits mode, so never follow it with another mode PATCH. Concurrent native state+ can still cause `mode_switch_blocked`. Read mode before eligibility (Direct has+ `sources: null`), and read each dependent write back. Runtime recovery, consent, source+ creation, mode and route writes are separate outcomes.++**Operation ownership at `08b82658bb` (not a universal mutation gate):**++| Setup operation | Actual dependency and admission |+| --- | --- |+| Runtime ensure/install/start; non-Hub `resumeGatewayAdoption` | Can call installer ensure. `runtime_start` also writes enabled intent and ensures before adapter start. Browser requests require fresh enabled config/support; server installer remains authoritative, including controller startup and other server-owned demand paths |+| API-key observe/create | Service `_observe_source_payload` provisions temporary material and probes through the adapter; create provisions and commits through `_commit_synced`. No installer ensure. With fresh healthy Hub, permit the existing form despite unsupported new installation; retain credential cleanup, nonce/unknown-write reconciliation and upstream failure semantics |+| OAuth start/status/submit and source completion | Existing OAuth owner calls its channel adapter. Hub adapter uses supervisor `client()`/`ensure_running()` on existing bytes and management endpoints; completion commits source projection. Native channel retains its separate auth/custody owner. No installer ensure in this flow. Keep single-flow, consent, cancellation, created-receipt and unknown-write handling |+| Mode change without native rows | `set_agent_mode` guards/drains native writers, rescans under lock and uses `_commit_synced`. No ensure; native rows are rejected, never silently taken over. Fresh health/config and mode readback remain required |+| Migration scan / apply | Full scan is discovery, not consent. New/incomplete `apply_native_migration._resume_takeover` explicitly ensures before native withdrawal and before sync/start; retain installing-path admission and journal recovery. A completed receipt replay returns before ensure. Healthy health alone cannot bypass this dependency; do not change migration semantics to remove it |+| Source/mode writes that change engine bindings | `_commit_synced` persists and calls adapter `sync_sources`; it waits for active transports and restarts a running engine via the existing verified disk binary, without installer ensure. Restart can fail if that binary/permissions/health is unavailable; owner restoration may also fail. Surface errors and re-read persisted config/runtime/receipts before retry, never claim atomic rollback |+| Exact route reads/preview/reorder | Pure chain reorder has unchanged bindings, so `_commit_synced` saves without restart or install. Keep exact-hop/menu-model eligibility, per-target guards and readback |++Thus a usable running Hub is not disabled merely by `manifest.resolution === 'unsupported'`.+New takeover can still be blocked by its real ensure dependency; manual sources, existing+OAuth and guarded no-native mode configuration remain available under their own guards.+An unsupported host with neither usable Hub nor an admitted recovery path cannot complete+the default journey. Read failures authorize neither lifecycle writes nor completion.++### Screen 3 — assistants (current thread `PRRT_kwDOPbFPYs6kOVg4`)++| Element | Producer → consumer and rule |+| --- | --- |+| installed | detect configured path and deep-refresh through the shared `createAgentCollectionReadAuthority` on active assistant entry and before completion; consume its current result as C4 specifies. Cached `listAgents` alone is insufficient. Hidden screens do not poll |+| install | explicit `api.installAgent(name)` then detect the returned/configured path and await the collection authority refresh/current result. Path/agent-config changes have the same refresh requirement. Pending/stale/failed refresh holds completion and exposes Retry; retain install output and one loading indicator |+| enabled | existing Switch config write, followed by `getBackendConnection` and Agent reads. Saved config reconciles live backends; no second restart |+| upgrade | `BackendLifecycleChip.onVisual` still owns probe/write, activity-gated; update coexists with enabled state |+| route control | **every installed/enabled assistant has an action**, including Direct, empty route, missing model and read failure. Enabled-capability setup opens Hub configuration/recovery: show its own `named_agents` model when routed, otherwise `onboarding.setup.configureRoute`. Opening requires no resolved route; mutations use C6 operation-specific admission/consent. Unsupported without running Hub offers recheck/guide, not native auth as a setup bypass. A disabled configuration retains C2 configuration recovery, never a Direct setup dialog. Busy operations may temporarily disable action |+| candidate identity | use the setup target policy below; identify backend + Agent name and exact menu model, independently of the global default. C4 may preserve a runnable custom default outside these edit targets |+| add model source | `onNavigate('providers')` preserves the dirty route draft and closes the route dialog; reopening restores it. Done returns focus to the invoking chip/configure action |+| all uninstalled | three install actions, workspace entry disabled, Back still available |++### Model-ranked route mapping — D4/D9 orchestrator-ratified technical interpretation++C2 keeps `RouteHop[]`: ordered `(source_id, upstream model_id)` pairs. A source with two+models yields two distinct rows. `putAgentSources` changes backend source membership and+priority; it is never the model-ranked Save operation. Existing `getAgentChain`,+`previewAgentChain`, `putAgentChain`, `putAgentModels` and `RouteChainDialog` supply the+primitives. The shared projection and multi-target coordinator are new L3 orchestration.++**Targets and scope.** Each installed/enabled backend card represents its designated builtin+default Agent. Use `listVibeAgents({cache:false})` for enabled/non-archived candidates and+`getVibeAgent(name,{cache:false})` for metadata: the brief list omits it. Match the store's+builtin selection (metadata `builtin_default` or `lock_delete`; prefer name equal to backend,+then `default`, then name order). A custom Agent merely named `claude` is not a builtin.+If none exists, keep configure reachable and require an explicit existing named-Agent target+selection; do not create or mutate an arbitrary Agent. Preserve each target Agent's exact+saved `model`; join to `AgentSupply.named_agents` by backend/name, then the exact+`catalog_models` menu id. No backend-native default or prefix-stripping inference.++The shared reorder includes the displayed setup targets, deduplicated by `(backend, menu+model)`, with their names/model identities visible before Save. It does not edit Agent model+fields, other menu-model chains, source order, disabled backends or the global default.+All Agents on the same backend/menu model necessarily share that chain: disclose their names+as affected; do not promise custom Agents with that same key are unaffected. A custom Agent+on a different menu model and a runnable global custom default are preserved. Explicit target+selection is required before adding such a custom route to the edit set.++**Fresh or unrouted target.** First ensure controller/runtime and mode as above; opening the+control itself has no route prerequisite. The server materializes recommendations for new+and legacy blank Agent models (`VibeAgentStore` creation/prefill); the UI never chooses the+first catalog row as an Agent model. Read back the actual selected model. If an anomalous+blank remains, require explicit Agent-model repair using existing Agent settings before+claiming a route target. The shipped Direct OpenCode recovery cannot perform this Hub repair.++Read the target's catalog and effective `getAgentChain`. Existing nonempty automatic or+manual chains hydrate immediately. If the exact saved menu id is absent (fresh OpenCode is+one real case), offer the existing catalog-add/manual form for **that exact id**, keeping the+current catalog as `baseline` and adding only the reviewed row through `putAgentModels`.+Use `getAgentModelCandidates` metadata for an exact matching candidate, or the existing+manual form's validated metadata/native protocol; never guess from the Agent name. If the+picker displays supplier chips, forward its `expected_suppliers` on catalog addition; a+manual row without a supplier promise omits that field. Preserve unrelated baseline rows+and read the catalog back before chain mutation. This adds a model entry, not an Agent-model+change; cancellation keeps the target unconfigured. Server admission errors remain visible.+For an empty chain, reuse the `routeCandidates`/`RouteChainDialog` exact-hop picker to select+an upstream model from an eligible source, preview it for this target, then save explicitly.+No arbitrary default hop, vendor-based cross-backend assumption or transplant from another+Agent. API-key passthrough can be an explicit manual target via the existing editor.++Example proved against the actual server: OpenCode's server-selected menu id+`openai/gpt-5.6-sol` can be admitted unchanged, then explicitly mapped to+`(source_id, 'gpt-5.6-sol')`. They are different identities. A source added on screen 2 can+supply an automatic route; it does not automatically extend a frozen manual chain. When an+existing manual route needs a new fallback, the same target-specific hop picker admits it+explicitly, then refreshes that target's membership. The shared reorder only reorders the+reviewed members; it never adds all global rows to every target.++**Initialization and reconciliation.** On the first clean open, snapshot for each target+`{ backend, modelId, agentNames, chain, manual_override }` from actual reads. Hydrate the+shared list by stable union of exact pairs: current global default's target first **only if+in the edit set**, then Claude/Codex/OpenCode and Agent name order. Preserve every target's+original membership and order as a baseline. Display the projected preferred/backup rank+for each affected target, not a claim that every row works on every backend. Divergent+existing orders remain unchanged on open/Done without an edit; show their actual orders and+the proposed outcome before an explicit shared Save. Disjoint native subscriptions retain+their disjoint subsets. A global interleaving change that alters no target is a no-op.++`routeOrder` and `routeOrderDirty` live in shell state. The single shared mounted route owner+retains target baselines, pending submissions and per-target results while hidden (local+state, not extra C2 fields or a new global store). Add source/Back closes the dialog without+unmounting this owner. Dirty re-entry retains both draft and baselines; read new server facts+separately, showing added candidates without overwriting edits. Changed Agent model, mode,+source membership or target set invalidates dependent previews and requires reconciliation.+If the owner is deliberately reset, clear the draft and baselines together, never retain an+orphaned dirty list. Refresh restores persisted truth, not an unpersisted browser draft.++**Projection, write and retry.** For each target, filter the shared order by that target's+reviewed exact-pair membership. Preserve temporarily unhealthy/stale persisted hops; the+server annotates health and admission. No empty write silently resets a chain: empty means+configuration/recovery required, because `{hops:[]}` removes the override and inherits defaults.+For changed targets preview with **`{manual_override:{hops}}`**. Server validation supplies+backend eligibility/model admission; inspect runnable/current and affected route evidence.+Do not synthesize vendor/protocol compatibility, auto-force interruption guards or hide a+failed target. A pure reorder keeps membership; actual backend eligibility changes may still+block it and require a fresh review.++Save only changed targets, in the displayed stable order, using `putAgentChain(backend,+menuModel,{hops})`. Reordering an automatic chain freezes that target as a manual override:+show the existing follows/frozen route explanation; future source additions will not silently+join it. Just opening or confirming an unchanged list never freezes an automatic chain.+Before each write re-read its Agent/model, mode and chain against the baseline. After each+write, read the exact target again and verify **manual_override and pair order**, not merely+the current healthy source. Reuse `routeChainMatchesAttempt` for identity/override matching.+A second-target failure leaves earlier confirmed writes intact and the shared draft dirty.+On retry read every attempted target: confirmed desired override/order is skipped; unchanged+baseline may be retried; any third state needs reconciliation/review. Unknown response means+read first. No cross-target rollback or atomicity claim. The API has no chain baseline/CAS;+a race after the last pre-read is an existing last-writer limitation, so the UI must detect+readback differences and must not promise exclusion of concurrent Settings writers.+Clear dirty only when every changed intended target is confirmed (or a verified no-op),+then refresh candidate supply/default readiness. A locally sorted list is never C4 evidence.++Temporary composed fixture evidence (real service persistence/preview/resolver with fake+engine, outside PR files): same source/two models remain distinct; native Claude/Codex subsets+remain separate; one builtin target edit preserves a custom Agent's different model/chain;+fresh Agent model materialization and OpenCode exact catalog/hop admission work; divergent+orders cause no opening write; second-target failure preserves the first write and retries+only the outstanding one. Existing primitive tests separately cover unknown-response+reconciliation, route guards and model prefill. Neither is a shipped setup integration test;+L3 must port these cases to its real consuming coordinator.++## Audit evidence and required consuming checks++| Repeated root class | Whole boundary audited / remaining evidence |+| --- | --- |+| route identity / eligibility / readiness | refreshed current CLI presence (existing generation owner) → action availability → named Agent+backend → mode → menu model → exact chain → default readback. C4/C6 define reachable configuration, explicit targets, exact-pair projection, partial-write/readback and default preservation; composed fixtures exercise the mapping |+| lifecycle / capability / readiness | enabled setup prerequisite → active-provider persistence → controller recovery/server admission → browser observation → operation-specific recovery/consent → readback. Default Hub requirement and independent healthy-Hub use are preserved; no unsupported-to-Direct conversion. `gatewayAdoption.test.ts` proves helper scope only; it is not a screen-2 preflight test. Future L2 tests must cover unsupported with zero runtime artifact installation/start, healthy-engine source writes and restart failure, already-Hub missing/stopped, real controller recovery (external composed fixture available), start failure and native blockers |+| producer / consumer / state | C2 React consuming test covers cross-screen state plus a late functional update. Full scan → transitive backend groups → complete apply IDs follows `MigrationDialog` and its grouping tests; L2 still needs a consuming integration test for discovery → owner confirmation → receipt/readback, including no implicit apply and unchanged Settings behavior |+| duplicated instructions / copy | plan §§4/9/10, C1 metadata and C2/C4/C6 reviewed together. Automatic runtime setup reuses approved precedent; owner D10 selects existing migration takeover and supersedes the handoff promises; setup owns only discovery/context/result presentation. Task-specific design source overrides the general default; existing theme shadow token replaces the literal prescription. Source-ranking substitution and false approval/rollback claims are removed; handoff remains unchanged user source |++PR0 tests do not claim a shipped screen or an end-to-end migration/route implementation.diff --git a/docs/plans/setup-three-screen/copy-contract.json b/docs/plans/setup-three-screen/copy-contract.jsonnew file mode 100644index 000000000..eab6dc626--- /dev/null+++ b/docs/plans/setup-three-screen/copy-contract.json@@ -0,0 +1,418 @@+{+ "_meta": {+ "contract": "C1 — setup three-screen copy",+ "status": "PR0 interface proposal. D10 owner-ratified on 2026-09-21 13:19 +08: reuse existing migration takeover; setup delegates through discovery/context and confirmed results. Selected copy under _migration_copy supersedes handoff copy-only, unchanged-connection and atomic-rollback promises for this flow. Source handoff unchanged; feature/merge authorization remains separate.",+ "source": "docs/plans/2026-09-21-setup-three-screen-handoff.md §4/§5/§8, reconciled against the strings already shipped on master 31c4e831b.",+ "ownership": {+ "onboarding.flow.*": "L1",+ "onboarding.welcome.* / onboarding.access.*": "L1",+ "onboarding.providers.* / onboarding.import.*": "L2",+ "onboarding.setup.* / onboarding.route.*": "L3"+ },+ "rules": [+ "PR0 adds no key to ui/src/i18n/*.json. Each lane lands the keys it owns together with the component that references them, because keyCoverage.test.ts reads the literal keys out of the app source.",+ "Every string that interpolates {{count}} ships a complete _one/_other family in BOTH bundles; zh repeats the same value so locale parity stays a plain set equality. This is the rule settings.models already enforces by test (copyAgreement.test.ts) and the class it exists to prevent.",+ "{{names}} is a joined list, so it may never be the subject of a singular verb in English.",+ "Orchestrator D8 allocates setup vocabulary separately from Settings. Owner D10 selects existing migration takeover on 2026-09-21 13:19 +08. Setup delegates confirmation/apply/recovery to that feature; no copy-only, unchanged-connection or atomic-rollback promise accompanies migration_apply.",+ "No string in this contract is a credential example. The prototype's sk-demo-example placeholder and its 交互演示,请勿输入真实凭据 / 正在保存模拟配置… lines are preview-only and must not ship (handoff §15).",+ "Model-ranked route rows use exact source/upstream-model pairs. C6 specifies displayed Agent/menu-model targets, backend subsets, divergent hydration and per-target readback. Shared does not mean every model is eligible for every assistant."+ ]+ },+ "_changed_existing": [+ {+ "key": "onboarding.welcome.title",+ "zh_before": "各有所长,接力完成",+ "en_before": "Great on their own. Better together",+ "zh_after": "各有所长,接力完成",+ "en_after": "Different strengths. One team.",+ "owner": "L1",+ "reason": "handoff §8 screen-1 row. zh already matches."+ },+ {+ "key": "onboarding.welcome.subtitle",+ "zh_before": "让 Claude Code、Codex、OpenCode 一起工作",+ "en_before": "Claude Code, Codex, and OpenCode — from planning to delivery",+ "zh_after": "让 Claude Code、Codex、OpenCode 一起工作",+ "en_after": "Bring Claude Code, Codex, and OpenCode together",+ "owner": "L1",+ "reason": "handoff §8 screen-1 row. zh already matches."+ },+ {+ "key": "onboarding.welcome.getStarted",+ "zh_before": "开始使用",+ "en_before": "Get started",+ "zh_after": "立即开始",+ "en_after": "Get started",+ "owner": "L1",+ "reason": "handoff §8 and the 2026-09-19 contract both name 立即开始; en already matches."+ },+ {+ "key": "onboarding.access.description",+ "zh_before": "手机 APP 和常用聊天应用,随时随地安排工作",+ "en_before": "Work on the go with the Avibe app or your favorite chat apps",+ "zh_after": "6个工作入口,随时随地安排工作",+ "en_after": "6 ways to work. Wherever you are.",+ "owner": "L1",+ "reason": "handoff §3/§8. The count is part of the sentence, not an interpolation: the tile list is a fixed six."+ },+ {+ "key": "onboarding.setup.title",+ "zh_before": "连接 AI,开始工作",+ "en_before": "Connect AI. Get to work",+ "zh_after": "选择你的 AI 助手",+ "en_after": "Choose your AI assistants",+ "owner": "L3",+ "reason": "handoff §5/§8. Supersedes the 2026-09-19 contract's connection heading, which described the two-step flow."+ },+ {+ "key": "onboarding.setup.subtitle",+ "zh_before": "安装助手,连接模型,即可开始工作",+ "en_before": "Install an assistant and connect a model to get started",+ "zh_after": "启用助手,确认默认模型,即可开始工作",+ "en_after": "Enable an assistant, confirm its default model, and start working",+ "owner": "L3",+ "reason": "handoff §5/§8. Connecting is screen 2's job now, so screen 3 no longer promises it."+ }+ ],+ "_reused_existing": [+ {+ "key": "common.cancel",+ "note": "add-dialog footer cancel"+ },+ {+ "key": "common.retry",+ "note": "add-dialog retry, gateway runtime retry, import failure retry"+ },+ {+ "key": "common.loading",+ "note": "generic pending reads"+ },+ {+ "key": "onboarding.setup.notInstalled",+ "note": "screen-3 pill 未安装 / Not installed already ships"+ },+ {+ "key": "onboarding.setup.enableNamed",+ "note": "screen-3 identity Switch label"+ },+ {+ "key": "onboarding.story.caption",+ "note": "回路字幕 规划 · 开发 · 测试 · 交付 already matches handoff §8"+ },+ {+ "key": "settings.models.importNotice.found_one / _other",+ "note": "capsule copy reused only with C6 complete-group/key-only unblocked count; a detected blocked key cannot be advertised as importable"+ },+ {+ "key": "settings.models.importNotice.help",+ "note": "capsule help link 什么是模型网关? / What is Model Hub?"+ },+ {+ "key": "settings.models.importNotice.dismiss",+ "note": "capsule X aria-label"+ },+ {+ "key": "settings.models.migration.blocked.*",+ "note": "per-item block reasons inside the import dialog; the setup scope changes the dialog's own chrome copy, not these explanations"+ },+ {+ "key": "settings.models.migration.errors.*",+ "note": "apply-failure explanations, same rule"+ },+ {+ "key": "settings.models.migration.notes.*",+ "note": "row secondary lines such as 含自定义 Base URL"+ },+ {+ "key": "settings.models.migration.source.*",+ "note": "row origin lines such as Codex 配置"+ }+ ],+ "bundle": {+ "zh": {+ "onboarding": {+ "flow": {+ "backToIntro": "返回介绍",+ "backToProviders": "返回模型",+ "gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。"+ },+ "providers": {+ "title": "添加模型提供商",+ "subtitle": "添加订阅或 API Key,由模型网关统一路由",+ "stageLabel": "提供商接入模型网关,再统一路由到助手",+ "gatewayName": "模型网关",+ "gatewayTagline": "模型一次接入,网关统一路由",+ "gatewayInstalling": "正在安装模型网关…",+ "gatewayStarting": "正在启动模型网关…",+ "gatewayNotReady": "模型网关未就绪,请重试",+ "cardKeyDetected": "检测到 API Key {{mask}}",+ "cardKeyAdded": "API Key {{mask}}",+ "cardSelected": "已选中",+ "cardUseExistingNamed": "使用 {{name}} 的已有配置",+ "cardAddSubscriptionNamed": "添加 {{name}} 的订阅或 API Key",+ "cardAddKeyNamed": "添加 {{name}} 的 API Key",+ "addMoreTitle": "添加更多",+ "addMoreSubtitle": "订阅 / API Key",+ "addMoreAction": "添加新的订阅或 API Key",+ "addMoreCount_one": "已添加 {{count}} 项",+ "addMoreCount_other": "已添加 {{count}} 项",+ "summaryNone": "未选择提供商",+ "summarySelected_one": "已选 {{count}} 个提供商:{{names}}",+ "summarySelected_other": "已选 {{count}} 个提供商:{{names}}",+ "summarySelectedNote": "确认迁移后,由模型网关管理所选助手的认证。",+ "summaryAdded_one": "已添加 {{count}} 个提供商:{{names}}",+ "summaryAdded_other": "已添加 {{count}} 个提供商:{{names}}",+ "summaryError": "连接未完成,请检查配置后重试。",+ "actionImport_one": "查看 {{count}} 项并继续",+ "actionImport_other": "查看 {{count}} 项并继续",+ "actionRetryImport_one": "查看 {{count}} 项迁移状态",+ "actionRetryImport_other": "查看 {{count}} 项迁移状态",+ "actionContinue": "继续,选择 AI 助手",+ "actionAdd": "添加订阅或 API Key",+ "actionConnecting": "正在连接…",+ "actionChecking": "正在检查连接…",+ "addTitle": "添加订阅或 API Key",+ "addTitleMore": "添加更多模型提供商",+ "addDescription": "添加一个来源即可开始,由模型网关统一路由。",+ "addDescriptionMore": "查看检测到的配置,确认后迁移,无需重新填写。",+ "addMethodsLabel": "添加方式",+ "addMethodDetected": "已检测到",+ "addMethodSubscription": "订阅",+ "addMethodApiKey": "API Key",+ "addDetectedNote": "查看全部关联配置并确认后开始迁移。其他无关设置会保留。",+ "addDetectedGroup": "其余已检测到的配置",+ "addDetectedSelectNamed": "选择 {{name}} 的已有配置",+ "addDetectedAdded": "已添加",+ "addSignInNamed": "通过 {{name}} 登录",+ "addSubscriptionNote": "前往服务商完成授权,无需在 Avibe 输入账号密码。",+ "addKeyLabelNamed": "{{name}} API Key",+ "addMoreProviders": "更多服务商",+ "addFooterAddKey": "添加",+ "addFooterAdd_one": "查看选中的 {{count}} 项",+ "addFooterAdd_other": "查看选中的 {{count}} 项",+ "addFooterSignInNamed": "前往 {{name}} 登录",+ "addFooterAdding": "添加中…",+ "addProgressSaving": "正在保存配置…",+ "addProgressChecking": "正在检查模型连接…",+ "addProgressWaitingAuth": "等待授权完成…",+ "addErrorPreserved": "连接未完成,输入已保留,请重试。",+ "addErrorDetectedPreserved": "操作未确认完成,选择已保留。请先检查当前状态,再继续恢复。",+ "gatewayUnsupported": "此设备无法安装模型网关。请重新检查可用性,或在受支持的环境中设置 Avibe。",+ "gatewayEnvironmentHelp": "查看安装指南"+ },+ "import": {+ "title": "迁移到模型网关",+ "description": "迁移后,CLI的认证信息将完全交由模型网关管理",+ "review": "查看并迁移",+ "helpBody": "模型网关统一管理认证和模型连接。迁移会清理已替代的原生认证,并将关联助手切换到模型网关;其他无关设置会保留。",+ "action_one": "查看选中的 {{count}} 项",+ "action_other": "查看选中的 {{count}} 项",+ "scopeNote": "此入口仅处理完整的 API Key 组。涉及订阅登录或阻塞项的关联组不可在此接管,请前往设置检查。",+ "progress_one": "正在迁移 {{count}} 项配置…",+ "progress_other": "正在迁移 {{count}} 项配置…",+ "progressDetail": "正在迁移认证并更新关联助手的连接",+ "done_one": "已迁移 {{count}} 项配置",+ "done_other": "已迁移 {{count}} 项配置",+ "doneDetail": "迁移和原生认证清理已完成。请确认助手的模型路由。",+ "remaining_one": "还有 {{count}} 项需要查看,可随时继续",+ "remaining_other": "还有 {{count}} 项需要查看,可随时继续",+ "remainingAction": "继续选择",+ "done": "完成",+ "confirm": "开始迁移",+ "notNow": "暂不迁移"+ },+ "setup": {+ "pillEnabled": "已启用",+ "pillNotEnabled": "未启用",+ "pillInstalling": "安装中",+ "pillUpdating": "升级中",+ "installedNotEnabled": "已安装,未启用",+ "actionInstall": "立即安装",+ "actionInstalling": "正在安装…",+ "actionUpdate": "立即升级",+ "defaultModel": "默认模型",+ "defaultModelNamed": "{{name}} 的模型路由,查看并调整顺序",+ "noteInstallNamed": "安装 {{name}},使用已添加的模型",+ "noteEnabled": "已启用,模型路由就绪后即可使用",+ "noteInstalledNotEnabled": "启用后即可使用已添加的模型",+ "enter": "进入工作台",+ "disabledNotice": "已停用,已有配置会保留",+ "configureRoute": "配置模型路由"+ },+ "route": {+ "title": "默认模型路由",+ "description": "为下列助手调整共享模型顺序。各助手按自己的模型列表依次尝试;其他路由保持不变。",+ "preferred": "首选",+ "backup": "备用 {{index}}",+ "singleNote": "此路由只有一个模型。可添加来源,再选择备用模型。",+ "addSource": "添加模型来源",+ "done": "完成",+ "moveUpNamed": "上移 {{name}}",+ "moveDownNamed": "下移 {{name}}"+ }+ }+ },+ "en": {+ "onboarding": {+ "flow": {+ "backToIntro": "Back to introduction",+ "backToProviders": "Back to models",+ "gatewayRequired": "Setup requires Model Hub to be enabled. Your saved configuration is unchanged. Restore it through your existing configuration controls, then retry."+ },+ "providers": {+ "title": "Add model providers",+ "subtitle": "Add a subscription or API Key. Model Hub handles routing.",+ "stageLabel": "Providers connect to Model Hub, which routes to assistants",+ "gatewayName": "Model Hub",+ "gatewayTagline": "Connect models once. Model Hub handles routing.",+ "gatewayInstalling": "Installing Model Hub…",+ "gatewayStarting": "Starting Model Hub…",+ "gatewayNotReady": "Model Hub is not ready. Try again.",+ "cardKeyDetected": "API key detected {{mask}}",+ "cardKeyAdded": "API Key {{mask}}",+ "cardSelected": "Selected",+ "cardUseExistingNamed": "Use existing {{name}} configuration",+ "cardAddSubscriptionNamed": "Add a {{name}} subscription or API Key",+ "cardAddKeyNamed": "Add a {{name}} API Key",+ "addMoreTitle": "Add more",+ "addMoreSubtitle": "Subscription / API Key",+ "addMoreAction": "Add a new subscription or API Key",+ "addMoreCount_one": "{{count}} added",+ "addMoreCount_other": "{{count}} added",+ "summaryNone": "No provider selected",+ "summarySelected_one": "{{count}} provider selected: {{names}}",+ "summarySelected_other": "{{count}} providers selected: {{names}}",+ "summarySelectedNote": "After migration is confirmed, Model Hub manages authentication for the selected assistants.",+ "summaryAdded_one": "{{count}} provider added: {{names}}",+ "summaryAdded_other": "{{count}} providers added: {{names}}",+ "summaryError": "Connection failed. Check your configuration and retry.",+ "actionImport_one": "Review {{count}} and continue",+ "actionImport_other": "Review {{count}} and continue",+ "actionRetryImport_one": "Review migration status for {{count}}",+ "actionRetryImport_other": "Review migration status for {{count}}",+ "actionContinue": "Continue to assistants",+ "actionAdd": "Add subscription or API Key",+ "actionConnecting": "Connecting…",+ "actionChecking": "Checking connection…",+ "addTitle": "Add subscription or API Key",+ "addTitleMore": "Add more model providers",+ "addDescription": "Add one source to get started. Model Hub handles routing.",+ "addDescriptionMore": "Review detected configurations and confirm migration without retyping.",+ "addMethodsLabel": "Add method",+ "addMethodDetected": "Detected",+ "addMethodSubscription": "Subscription",+ "addMethodApiKey": "API Key",+ "addDetectedNote": "Review all linked configurations and confirm to start migration. Unrelated settings are preserved.",+ "addDetectedGroup": "Other detected configurations",+ "addDetectedSelectNamed": "Select existing {{name}} configuration",+ "addDetectedAdded": "Added",+ "addSignInNamed": "Sign in with {{name}}",+ "addSubscriptionNote": "Authorize with the provider. You do not enter your password in Avibe.",+ "addKeyLabelNamed": "{{name}} API Key",+ "addMoreProviders": "More providers",+ "addFooterAddKey": "Add",+ "addFooterAdd_one": "Review {{count}} selected",+ "addFooterAdd_other": "Review {{count}} selected",+ "addFooterSignInNamed": "Sign in with {{name}}",+ "addFooterAdding": "Adding…",+ "addProgressSaving": "Saving configuration…",+ "addProgressChecking": "Checking the model connection…",+ "addProgressWaitingAuth": "Waiting for authorization…",+ "addErrorPreserved": "Connection failed. Your entries are preserved. Please retry.",+ "addErrorDetectedPreserved": "Completion is unconfirmed. Your selection is preserved. Check the current state before continuing recovery.",+ "gatewayUnsupported": "Model Hub cannot be installed on this device. Recheck availability or set up Avibe in a supported environment.",+ "gatewayEnvironmentHelp": "View installation guide"+ },+ "import": {+ "title": "Migrate to Model Hub",+ "description": "After migration, CLI authentication will be managed entirely by Model Hub.",+ "review": "Review migration",+ "helpBody": "Model Hub manages authentication and model connections. Migration removes replaced native authentication and switches linked assistants to Model Hub; unrelated settings are preserved.",+ "action_one": "Review {{count}} selected",+ "action_other": "Review {{count}} selected",+ "scopeNote": "This entry handles complete API-key groups only. Linked groups with subscription sign-ins or blockers cannot be taken over here; review them in Settings.",+ "progress_one": "Migrating {{count}} configuration item…",+ "progress_other": "Migrating {{count}} configuration items…",+ "progressDetail": "Migrating authentication and updating linked assistant connections",+ "done_one": "Migrated {{count}} configuration item",+ "done_other": "Migrated {{count}} configuration items",+ "doneDetail": "Migration and native authentication cleanup are complete. Check the assistants’ model routes.",+ "remaining_one": "{{count}} item needs review. Continue any time.",+ "remaining_other": "{{count}} items need review. Continue any time.",+ "remainingAction": "Review remaining",+ "done": "Done",+ "confirm": "Start migration",+ "notNow": "Not now"+ },+ "setup": {+ "pillEnabled": "Enabled",+ "pillNotEnabled": "Not enabled",+ "pillInstalling": "Installing",+ "pillUpdating": "Updating",+ "installedNotEnabled": "Installed, not enabled",+ "actionInstall": "Install",+ "actionInstalling": "Installing…",+ "actionUpdate": "Update now",+ "defaultModel": "Default model",+ "defaultModelNamed": "Model route for {{name}}, review and reorder",+ "noteInstallNamed": "Install {{name}} to use the models you added",+ "noteEnabled": "Enabled. Ready to work once its model route is ready.",+ "noteInstalledNotEnabled": "Enable to use the models you added",+ "enter": "Open workspace",+ "disabledNotice": "Disabled. Your saved configuration stays.",+ "configureRoute": "Configure model route"+ },+ "route": {+ "title": "Default model route",+ "description": "Set a shared model order for the assistants shown below. Each tries its own model subset in that order; other routes stay unchanged.",+ "preferred": "Preferred",+ "backup": "Backup {{index}}",+ "singleNote": "This route has one model. Add a source, then select a backup model.",+ "addSource": "Add model source",+ "done": "Done",+ "moveUpNamed": "Move {{name}} up",+ "moveDownNamed": "Move {{name}} down"+ }+ }+ }+ },+ "_migration_copy": {+ "decision": "D10 owner-ratified 2026-09-21 13:19 +08: setup owns the default Hub journey and consumes the existing migration takeover feature. Its confirmation, native cleanup, custody/mode transition, transaction and journal recovery retain their existing owners; no setup-specific migration mechanism.",+ "keys": [+ "onboarding.providers.summarySelectedNote",+ "onboarding.providers.addDetectedNote",+ "onboarding.providers.addErrorDetectedPreserved",+ "onboarding.import.description",+ "onboarding.import.helpBody",+ "onboarding.import.scopeNote",+ "onboarding.import.progress_one",+ "onboarding.import.progress_other",+ "onboarding.import.progressDetail",+ "onboarding.import.done_one",+ "onboarding.import.done_other",+ "onboarding.import.doneDetail",+ "onboarding.providers.addDescriptionMore",+ "onboarding.providers.actionImport_one",+ "onboarding.providers.actionImport_other",+ "onboarding.providers.actionRetryImport_one",+ "onboarding.providers.actionRetryImport_other",+ "onboarding.providers.addFooterAdd_one",+ "onboarding.providers.addFooterAdd_other",+ "onboarding.import.title",+ "onboarding.import.review",+ "onboarding.import.confirm",+ "onboarding.import.notNow",+ "onboarding.import.action_one",+ "onboarding.import.action_other",+ "onboarding.import.remaining_one",+ "onboarding.import.remaining_other"+ ],+ "behavior": [+ "Cards, capsule, Detected tab and migration-entry CTA delegate selection/context to the existing complete-group review. Setup entry, selection, normal navigation and runtime install/start never apply credentials. Only Start migration confirms; Not now keeps native authentication and mode unchanged.",+ "Show the exact approved consequence sentence from model-hub-native-takeover.md. MigrationDialog/grouping and modelsApi scan/apply delegate to service migration_apply, apply_native_migration and its journal; they own cleanup, custody, Hub mode/placement and recovery. No second mode PATCH after successful apply; unrelated settings stay preserved.",+ "Setup entry remains API-key-only: show but block whole groups containing OAuth or non-importable rows. The broader migration feature remains in Settings. Counts are confirmed migration items, not inferred keys or Sources.",+ "Setup refreshes real sources/supplies and updates presentation from confirmed receipts; zero/error refresh callbacks are not completed takeover. Unknown or failed apply stays with the existing migration recovery owner. No setup-specific retry engine, custom rollback, copy-only or unchanged-assistant-connections promise.",+ "Only minimal controlled-state/copy adaptation of the existing migration feature is planned. Original handoff content remains unchanged; the selected contract supersedes its incompatible migration promises. D10 ratification grants no feature dispatch, merge or real-credential migration authority to PR0."+ ]+ }+}diff --git a/ui/src/components/onboarding/setupFlow.test.ts b/ui/src/components/onboarding/setupFlow.test.tsnew file mode 100644index 000000000..8a3250a50--- /dev/null+++ b/ui/src/components/onboarding/setupFlow.test.ts@@ -0,0 +1,315 @@+// @vitest-environment jsdom+// Contract consumers live only in this test; PR0 introduces no feature shell.+import { createElement, useState } from 'react';+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { beginRegionRead, failRegionRead, loadingRegion, readyRegion, unreadRegion } from '../settings/models/regionRead';+import { CONTRACT_VERSION, type RuntimeDependency } from '../settings/models/types';++import {+ INITIAL_SETUP_FLOW_STATE,+ SETUP_SCREENS,+ setupBackTarget,+ setupCanAttemptInstall,+ setupCandidateAllowed,+ setupHubRunning,+ setupCapability,+ setupNavigationReady,+ type SetupCapability,+ type SetupFlowState,+ type SetupScreenId,+ type SetupScreenProps,+} from './setupFlow';++afterEach(cleanup);++const CAPABILITIES: readonly SetupCapability[] = ['pending', 'enabled', 'disabled'];++describe('one Hub setup journey', () => {+ it('keeps every step and requires enabled capability to progress', () => {+ expect(SETUP_SCREENS).toEqual(['intro', 'providers', 'assistants']);+ for (const capability of CAPABILITIES) {+ expect(setupNavigationReady(capability, true)).toBe(capability === 'enabled');+ }+ });++ it('distinguishes unread capability from an authoritative disabled configuration', () => {+ expect(setupCapability(null)).toBe('pending');+ expect(setupCapability(true)).toBe('enabled');+ expect(setupCapability(false)).toBe('disabled');+ });++ it('keeps Back on the same three-screen path', () => {+ expect(setupBackTarget(SETUP_SCREENS, 'assistants')).toBe('providers');+ expect(setupBackTarget(SETUP_SCREENS, 'providers')).toBe('intro');+ expect(setupBackTarget(SETUP_SCREENS, 'intro')).toBeNull();+ });+});++describe('shell-owned flow state', () => {+ it('starts with nothing selected, imported, added or ordered, and no dirty draft', () => {+ expect(INITIAL_SETUP_FLOW_STATE).toEqual({+ providerSelection: { scan: null, selectedBackends: [] },+ importedCount: 0,+ addedThroughMore: [],+ routeOrder: [],+ routeOrderDirty: false,+ });+ });++ it('carries screen updates through navigation and composes a late functional update with newer state', async () => {+ let finishImport: (() => void) | undefined;+ const pendingImport = new Promise<void>((resolve) => { finishImport = resolve; });+ const draft = [+ { source_id: '来源-一', model_id: '模型-首选' },+ { source_id: '来源-一', model_id: '模型-备用' },+ ];+ const selection: SetupFlowState['providerSelection'] = {+ scan: { items: [+ { id: 'key-a', backend: 'opencode', kind: 'opencode_provider', masked_detail: 'fixture…0001', proposed_action: 'import', selected: true },+ { id: 'key-b', backend: 'opencode', kind: 'opencode_provider', masked_detail: 'fixture…0002', proposed_action: 'import', selected: true },+ ] },+ selectedBackends: ['opencode'],+ };+ const ProviderScreen = ({ active, flowState, setFlowState, onNavigate }: SetupScreenProps) =>+ createElement('section', { hidden: !active, inert: !active, 'data-testid': 'providers' },+ createElement('output', null, JSON.stringify(flowState)),+ createElement('button', { onClick: () => {+ setFlowState((previous) => ({ ...previous, providerSelection: selection }));+ // Deliberately settle after another screen has edited the draft.+ void pendingImport.then(() => setFlowState((previous) => ({+ ...previous, importedCount: previous.importedCount + 2,+ providerSelection: { scan: null, selectedBackends: [] },+ })));+ onNavigate('assistants');+ } }, 'Start fixture import'),+ createElement('button', { onClick: () => {+ setFlowState((previous) => ({ ...previous, addedThroughMore: ['新增来源'] }));+ onNavigate('assistants');+ } }, 'Add fixture source'));+ const AssistantScreen = ({ active, flowState, setFlowState, onNavigate }: SetupScreenProps) =>+ createElement('section', { hidden: !active, inert: !active, 'data-testid': 'assistants' },+ createElement('output', null, JSON.stringify(flowState)),+ createElement('button', { onClick: () => {+ setFlowState((previous) => ({ ...previous, routeOrder: draft, routeOrderDirty: true }));+ onNavigate('providers');+ } }, 'Edit fixture route'));+ const Shell = () => {+ const [current, setCurrent] = useState<SetupScreenId>('providers');+ const [flowState, setFlowState] = useState(INITIAL_SETUP_FLOW_STATE);+ const common: Omit<SetupScreenProps, 'active'> = {+ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion(), onRetrySetup: () => {},+ flowState, setFlowState, handoff: false, onNavigate: setCurrent, onActionChange: () => {},+ };+ return createElement('main', null,+ createElement(ProviderScreen, { ...common, active: current === 'providers' }),+ createElement(AssistantScreen, { ...common, active: current === 'assistants' }));+ };+ render(createElement(Shell));+ const read = (id: string): SetupFlowState => JSON.parse(within(screen.getByTestId(id)).getByRole('status').textContent!);++ fireEvent.click(screen.getByRole('button', { name: 'Start fixture import' }));+ expect(read('assistants').providerSelection).toEqual(selection);+ fireEvent.click(screen.getByRole('button', { name: 'Edit fixture route' }));+ expect(read('providers')).toMatchObject({ providerSelection: selection, routeOrder: draft, routeOrderDirty: true });+ fireEvent.click(screen.getByRole('button', { name: 'Add fixture source' }));+ await act(async () => { finishImport!(); await pendingImport; });+ expect(read('assistants')).toEqual({+ providerSelection: { scan: null, selectedBackends: [] }, importedCount: 2,+ addedThroughMore: ['新增来源'], routeOrder: draft, routeOrderDirty: true,+ });+ expect((screen.getByTestId('providers') as HTMLElement).hidden).toBe(true);+ expect(screen.getByTestId('providers').hasAttribute('inert')).toBe(true);+ });+});++const runtime = (+ resolution: RuntimeDependency['manifest']['resolution'],+ health: RuntimeDependency['status']['health'] = 'not_installed',+): RuntimeDependency => ({+ contract_version: CONTRACT_VERSION, enabled: true,+ manifest: resolution === 'unresolved'+ ? { name: 'cliproxyapi', resolution, assets: [] }+ : { name: 'cliproxyapi', resolution, version: 'fixture', source_sha: 'fixture', assets: [] },+ status: { verified: false, health },+});++it('keeps Hub readiness independent of install admission and requires the deployment-selected mode', () => {+ const healths: RuntimeDependency['status']['health'][] = ['ok', 'degraded', 'down', 'not_started', 'not_installed', 'installing'];+ for (const health of healths) {+ const read = readyRegion(runtime('unsupported', health));+ expect(setupCanAttemptInstall('enabled', true, read)).toBe(false);+ expect(setupCandidateAllowed('enabled', true, read, 'direct')).toBe(false);+ expect(setupCandidateAllowed('enabled', true, read, 'hub')).toBe(health === 'ok' || health === 'degraded');+ }+ for (const resolution of ['resolved', 'unresolved'] as const) {+ expect(setupCanAttemptInstall('enabled', true, readyRegion(runtime(resolution)))).toBe(true);+ }+ for (const capability of ['pending', 'disabled'] as const) {+ expect(setupCanAttemptInstall(capability, true, readyRegion(runtime('resolved')))).toBe(false);+ expect(setupCandidateAllowed(capability, true, readyRegion(runtime('resolved', 'ok')), 'hub')).toBe(false);+ }+ expect(setupCandidateAllowed('disabled', true, unreadRegion(), 'direct')).toBe(false);+ expect(setupCandidateAllowed('disabled', true, unreadRegion(), undefined)).toBe(false);+ const stoppedIntent = readyRegion({ ...runtime('resolved', 'ok'), enabled: false });+ expect(setupCanAttemptInstall('enabled', true, stoppedIntent)).toBe(false);+ expect(setupCandidateAllowed('enabled', true, stoppedIntent, 'hub')).toBe(false);+ expect(setupNavigationReady('enabled', null)).toBe(false);+ expect(setupNavigationReady('enabled', false)).toBe(false);+});++// Test-only consumers of C2 and its actual gates; synthetic route/auth/application+// readiness below does not prove backend readiness or a shipped feature coordinator.+type Observation = Pick<SetupScreenProps, 'capability' | 'gatewayEnabled' | 'runtimeRead'>;+function RuntimeConsumer({ active, capability, runtimeRead, flowState, setFlowState, onRetrySetup }: SetupScreenProps) {+ return createElement('section', { hidden: !active, inert: !active },+ createElement('output', { 'aria-label': 'draft' }, JSON.stringify(flowState)),+ createElement('output', { 'aria-label': 'capability' }, capability),+ createElement('output', { 'aria-label': 'runtime read' }, runtimeRead.kind),+ createElement('button', { onClick: () => setFlowState((previous) => ({+ ...previous, routeOrder: [{ source_id: 'src_fixture1', model_id: '模型' }], routeOrderDirty: true,+ })) }, 'Edit draft'),+ createElement('button', { onClick: onRetrySetup }, 'Recheck runtime'));+}+function RuntimeHarness({ capture, retry, install, complete, mode }: {+ capture: (settle: (observation: Observation) => void) => void;+ // Synthetic result of the shell's config-first retry owner; no real HTTP here.+ retry: () => Promise<Observation>;+ install: () => void;+ complete: () => void;+ mode: 'direct' | 'hub';+}) {+ const [observation, setObservation] = useState<Observation>({ capability: 'pending', gatewayEnabled: null, runtimeRead: loadingRegion() });+ const [current, setCurrent] = useState<SetupScreenId>('intro');+ const [flowState, setFlowState] = useState(INITIAL_SETUP_FLOW_STATE);+ capture(setObservation);+ const { capability, gatewayEnabled, runtimeRead } = observation;+ const sequence = SETUP_SCREENS;+ const back = setupBackTarget(sequence, current);+ const mayContinue = setupNavigationReady(capability, gatewayEnabled) && (current === 'intro'+ || (current === 'providers' ? setupHubRunning(runtimeRead) : setupCandidateAllowed(capability, gatewayEnabled, runtimeRead, mode)));+ const common: Omit<SetupScreenProps, 'active'> = {+ ...observation, flowState, setFlowState, handoff: false, onActionChange: () => {}, onNavigate: setCurrent,+ onRetrySetup: () => {+ setObservation((previous) => ({ ...previous, runtimeRead: beginRegionRead(previous.runtimeRead) }));+ void retry().then(+ (result) => setObservation(result),+ () => setObservation((previous) => ({ ...previous, runtimeRead: failRegionRead(previous.runtimeRead) })),+ );+ },+ };+ return createElement('main', null,+ createElement('output', { 'aria-label': 'current screen' }, current),+ ...SETUP_SCREENS.map((id) => createElement(RuntimeConsumer, { ...common, key: id, active: id === current })),+ createElement('button', { disabled: !mayContinue, onClick: () => {+ if (current === 'assistants') complete();+ else setCurrent(sequence[sequence.indexOf(current) + 1]);+ } }, 'Primary'),+ createElement('button', { disabled: !back, onClick: () => { if (back) setCurrent(back); } }, 'Back'),+ createElement('button', { disabled: !setupCanAttemptInstall(capability, gatewayEnabled, runtimeRead), onClick: install }, 'Prepare runtime'));+}+const output = (name: string) => screen.getByRole('status', { name }).textContent;+const primary = () => screen.getByRole('button', { name: 'Primary' }) as HTMLButtonElement;++it('consumes unsupported admission without leaving providers, losing drafts or completing through Direct', async () => {+ let settle!: (observation: Observation) => void;+ const install = vi.fn(); const complete = vi.fn();+ const retry = vi.fn().mockResolvedValue({ capability: 'enabled', gatewayEnabled: true, runtimeRead: readyRegion(runtime('resolved', 'ok')) });+ const props = { capture: (value: typeof settle) => { settle = value; }, retry, install, complete };+ const view = render(createElement(RuntimeHarness, { ...props, mode: 'direct' }));+ expect(primary().disabled).toBe(true);+ act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion() }));+ fireEvent.click(primary()); // Support is first learned after provider bootstrap.+ expect(output('current screen')).toBe('providers');+ fireEvent.click(screen.getByRole('button', { name: 'Edit draft' }));+ const draft = output('draft');+ act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: readyRegion(runtime('unsupported')) }));+ expect(output('current screen')).toBe('providers');+ expect(primary().disabled).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Prepare runtime' }));+ expect(install).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ expect(output('current screen')).toBe('intro');+ fireEvent.click(primary());+ expect(output('current screen')).toBe('providers');+ expect(output('draft')).toBe(draft);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Recheck runtime' })); });+ expect(retry).toHaveBeenCalledOnce();+ expect(output('runtime read')).toBe('ready');+ expect(output('current screen')).toBe('providers');+ fireEvent.click(primary());+ expect(output('current screen')).toBe('assistants');+ expect(primary().disabled).toBe(true); // A healthy runtime alone never changes Direct custody.+ fireEvent.click(primary());+ expect(complete).not.toHaveBeenCalled();+ view.rerender(createElement(RuntimeHarness, { ...props, mode: 'hub' })); // Fresh persisted-mode evidence.+ expect(primary().disabled).toBe(false);+ expect(output('draft')).toBe(draft);+ fireEvent.click(primary());+ expect(complete).toHaveBeenCalledOnce();+});++it('consumes read failures as held errors, retries in place and preserves a healthy install-unsupported Hub', async () => {+ let settle!: (observation: Observation) => void;+ const retry = vi.fn().mockRejectedValueOnce(new Error('fixture 503'))+ .mockResolvedValue({ capability: 'enabled', gatewayEnabled: true, runtimeRead: readyRegion(runtime('unsupported', 'ok')) });+ const complete = vi.fn(); const install = vi.fn();+ render(createElement(RuntimeHarness, { capture: (value) => { settle = value; }, retry, complete, install, mode: 'hub' }));+ act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion() }));+ fireEvent.click(primary());+ for (const read of [unreadRegion<RuntimeDependency>(), beginRegionRead(readyRegion(runtime('resolved', 'ok'))), failRegionRead(readyRegion(runtime('unsupported', 'ok')))]) {+ act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: read }));+ expect(output('current screen')).toBe('providers');+ expect(output('capability')).toBe('enabled');+ expect(primary().disabled).toBe(true);+ expect(setupCanAttemptInstall('enabled', true, read)).toBe(false);+ expect(setupCandidateAllowed('enabled', true, read, 'direct')).toBe(false);+ expect(setupCandidateAllowed('enabled', true, read, 'hub')).toBe(false);+ }+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Recheck runtime' })); });+ expect(output('capability')).toBe('enabled');+ expect(primary().disabled).toBe(true);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Recheck runtime' })); });+ expect(output('runtime read')).toBe('ready');+ fireEvent.click(screen.getByRole('button', { name: 'Prepare runtime' }));+ expect(install).not.toHaveBeenCalled();+ fireEvent.click(primary());+ expect(output('current screen')).toBe('assistants');+ fireEvent.click(primary());+ expect(complete).toHaveBeenCalledOnce();+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ expect(output('current screen')).toBe('providers');+});+++it.each(['deployment', 'saved-intent'] as const)('holds disabled %s without skipping providers or treating Direct as setup-ready', async (disabled) => {+ const config = { capability: disabled === 'deployment' ? 'disabled' as const : 'enabled' as const, gatewayEnabled: disabled !== 'saved-intent' };+ let settle!: (observation: Observation) => void;+ const complete = vi.fn(); const install = vi.fn();+ const retry = vi.fn().mockResolvedValue({ ...config, runtimeRead: loadingRegion() });+ render(createElement(RuntimeHarness, { capture: (value) => { settle = value; }, retry, complete, install, mode: 'direct' }));+ act(() => settle({ ...config, runtimeRead: readyRegion(runtime('resolved', 'ok')) }));+ expect(output('current screen')).toBe('intro');+ expect(primary().disabled).toBe(true);+ fireEvent.click(primary());+ fireEvent.click(screen.getByRole('button', { name: 'Prepare runtime' }));+ expect(complete).not.toHaveBeenCalled();+ expect(install).not.toHaveBeenCalled();+ expect(output('capability')).toBe(config.capability);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Recheck runtime' })); });+ expect(retry).toHaveBeenCalledOnce();+ expect(output('capability')).toBe(config.capability);+ expect(primary().disabled).toBe(true);+ // A disabled result arriving later holds the current screen, never redirects to Direct.+ act(() => settle({ capability: 'enabled', gatewayEnabled: true, runtimeRead: loadingRegion() }));+ fireEvent.click(primary());+ fireEvent.click(screen.getByRole('button', { name: 'Edit draft' }));+ const draft = output('draft');+ act(() => settle({ ...config, runtimeRead: readyRegion(runtime('resolved', 'ok')) }));+ expect(output('current screen')).toBe('providers');+ expect(primary().disabled).toBe(true);+ expect(output('draft')).toBe(draft);+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ expect(output('current screen')).toBe('intro');+ expect(output('capability')).toBe(config.capability);+});diff --git a/ui/src/components/onboarding/setupFlow.ts b/ui/src/components/onboarding/setupFlow.tsnew file mode 100644index 000000000..509b13299--- /dev/null+++ b/ui/src/components/onboarding/setupFlow.ts@@ -0,0 +1,201 @@+/**+ * C2 — the setup flow's interface contract.+ *+ * Proposed for `master` before the three-screen lanes fork, so a lane reads one shared+ * declaration instead of transcribing a shape out of a plan document. Everything here is+ * cross-lane by construction: the shell (L1) renders it, the providers screen (L2) and the+ * assistants screen (L3) implement against it. A deviation needs orchestrator sign-off+ * BEFORE the edit, not a reconciling commit afterwards.+ *+ * The binding prose that goes with these types — geometry and DOM hooks (C3), the entry+ * gate (C4), the stable dialog frame (C5) and the field-by-field data mapping (C6) — lives+ * in `docs/plans/setup-three-screen/contracts.md`. Copy lives in+ * `docs/plans/setup-three-screen/copy-contract.json` (C1).+ */+import type { Dispatch, SetStateAction } from 'react';+import type { TranslationKey } from '@/i18n/types';+import type { AgentBackend, MigrationScan, RouteHop, RuntimeDependency } from '../settings/models/types';+import { foldRegionRead, type RegionRead } from '../settings/models/regionRead';+import { runtimeCanAttemptInstall, runtimeIsRunning } from '../settings/models/runtimeLifecycle';++/** The flow's order. A screen id, not an index: `Wizard.tsx` used to hold `'welcome' |+ * 'agents'`, and an index-based step cannot survive a screen being added or skipped. */+export const SETUP_SCREENS = ['intro', 'providers', 'assistants'] as const;+export type SetupScreenId = (typeof SETUP_SCREENS)[number];++/**+ * Which transition is playing, or `false` when none is. Named for the screen being+ * ENTERED, because the snapshot is taken from the screen being left: `providers` shrinks+ * the story cards into the destination row, `assistants` lifts that row into full cards.+ */+export type SetupHandoffTarget = Exclude<SetupScreenId, 'intro'>;++/** The leading glyph the shell draws inside the primary action. */+export type SetupActionIcon = 'none' | 'arrow-right' | 'spinner';++/**+ * One screen's claim on the shell's primary action. The shell owns the element — that is+ * what makes "the button never moves" a property of the tree rather than an agreement+ * between two stylesheets — so a screen describes the button and never renders it.+ *+ * `labelKey` is a key from C1. It is typed against the live bundle, so a screen cannot+ * name a string that has not shipped.+ */+export type SetupAction = {+ labelKey: TranslationKey;+ /** Interpolation values for `labelKey`, e.g. `{ count: 2 }` or `{ name: 'Codex' }`. */+ labelArgs?: Record<string, string | number>;+ disabled: boolean;+ /** Renders the spinner glyph and suppresses the arrow. Distinct from `disabled`: a busy+ * action is also disabled, but a disabled one is not necessarily busy. */+ busy: boolean;+ icon: SetupActionIcon;+};++/**+ * How the shell drives the active screen. The primary action is the shell's, so the click+ * has to be handed down; a screen decides what the click MEANS (import the batch, continue,+ * open the add dialog, enter the workspace).+ */+export type SetupScreenHandle = {+ activate: () => void;+};++export type SetupScreenProps = {+ /** Mounted does not mean active: hidden/inert screens retain drafts but must not start+ * mutations, poll, claim actions, navigate or run authorization effects (C2).+ * D11 bootstrap runs only on active provider entry with capability enabled;+ * intro mount alone never seeds config or starts services. */+ active: boolean;+ handoff: SetupHandoffTarget | false;+ capability: SetupCapability;+ /** Fresh config.model_hub.enabled: persisted user intent, separate from deployment capability. */+ gatewayEnabled: boolean | null;+ /** Shell-owned authoritative runtime read. Host admission never changes capability+ * or the screen sequence. Stale/error reads authorize no installation or Hub entry. */+ runtimeRead: RegionRead<RuntimeDependency>;+ /** Re-read config, then resume the existing bootstrap/runtime owner only if enabled.+ * Preserve drafts and never re-enable a disabled configuration automatically. */+ onRetrySetup: () => void;+ flowState: SetupFlowState;+ /** Pass the shell's React setter. Screens use functional updates to preserve changes+ * made by other screens while an asynchronous operation was pending. */+ setFlowState: Dispatch<SetStateAction<SetupFlowState>>;+ /** Bound to this screen by the shell; ignore publications from an inactive screen or+ * an obsolete activation. Only the active screen's handle may receive a click. */+ onActionChange: (action: SetupAction) => void;+ /** Request a screen change. The shell decides whether to play a handoff. */+ onNavigate: (screen: SetupScreenId) => void;+};++/** One scan snapshot plus whole-backend consent. The full scan is needed to expand+ * required_backends transitively and expose blockers; never store only visible keys.+ * selectedBackends is the union of complete, unblocked consent groups (C6), not a+ * per-row selection. L2 must adapt the existing MigrationDialog owner to this controlled+ * state before using it in setup; its shipped props do not yet accept this shape. */+export type SetupProviderSelection = {+ scan: MigrationScan | null;+ selectedBackends: AgentBackend[];+};++/**+ * State the SHELL owns, because it has to outlive any single screen: leaving screen 2 for+ * screen 3 and coming back must find the same selection, the same cumulative import count+ * and the same route order (handoff §5 "状态保留"). Anything the server already owns —+ * installed CLIs, enabled backends, persisted sources — is read, never mirrored here.+ */+export type SetupFlowState = {+ /** Ephemeral scan/consent draft. Replace on a fresh scan and reconcile whole groups;+ * clear confirmed groups after apply. No credential material lives in this state. */+ providerSelection: SetupProviderSelection;+ /** Cumulative confirmed `MigrationApplyResult.applied`, counted once per submitted+ * batch. It counts migration items, not necessarily keys or created sources (C6). */+ importedCount: number;+ /** Source ids added through the "Add more" card, which is what its badge counts. */+ addedThroughMore: string[];+ /** Model-ranked working draft: each row identifies BOTH source and upstream model.+ * This is not a putAgentSources payload. C6/D4/D9 specify explicit Agent/menu-model+ * targets and projection through each target's reviewed exact-hop membership. The+ * shared mounted route owner retains target baselines and pending write receipts;+ * this list alone cannot reconstruct them or justify a source-priority write.+ * Hydrate only while clean; a dirty draft survives navigation and is cleared only+ * after every intended write is read back. Empty means no hydrated draft, not no+ * server route. C4 never gates entry on this client draft. */+ routeOrder: RouteHop[];+ /** Whether `routeOrder` holds an edit the server has not confirmed. Decides if a re-entry+ * may hydrate; all intended writes must be confirmed before clearing it. */+ routeOrderDirty: boolean;+};++export const INITIAL_SETUP_FLOW_STATE: SetupFlowState = {+ providerSelection: { scan: null, selectedBackends: [] },+ importedCount: 0,+ addedThroughMore: [],+ routeOrder: [],+ routeOrderDirty: false,+};++/**+ * The capability read as a three-state, because two states cannot express "no authoritative+ * answer yet".+ *+ * The producer matters: `disabled` must mean an authoritative read that says the deployment+ * turned Model Hub off, never a request that failed. `useModelHubCapability()` catches its+ * own error and resolves to `false`, so it cannot distinguish the two and is NOT a safe+ * producer here; derive the value from the config the Wizard has already loaded+ * (`modelHubEnabledFromConfig`, after verifying capabilities.model_hub.enabled is a boolean;+ * that helper also returns false for missing fields). This is the same projection+ * `readOpencodeSetupRoutes` uses; a successful config read plus the explicit boolean supplies+ * the authority. Anything less stays `pending`. Setup requires enabled capability;+ * disabled is a configuration boundary, never a Direct setup branch.+ */+export type SetupCapability = 'pending' | 'enabled' | 'disabled';++export const setupCapability = (modelHubEnabled: boolean | null): SetupCapability =>+ modelHubEnabled === null ? 'pending' : modelHubEnabled ? 'enabled' : 'disabled';++/** Setup has one fixed SETUP_SCREENS journey. Capability/runtime never remove a step.+ * Disabled configuration is preserved and requires recovery, not Direct completion. */+export const setupNavigationReady = (capability: SetupCapability, gatewayEnabled: boolean | null): boolean =>+ capability === 'enabled' && gatewayEnabled === true;++/** Fresh install admission; unresolved manifests may still be installable. */+export const setupCanAttemptInstall = (+ capability: SetupCapability,+ gatewayEnabled: boolean | null,+ runtimeRead: RegionRead<RuntimeDependency>,+): boolean => setupNavigationReady(capability, gatewayEnabled) && foldRegionRead(runtimeRead, {+ loading: () => false,+ unread: () => false,+ degraded: () => false,+ ready: (runtime) => runtime.enabled !== false && runtimeCanAttemptInstall(runtime),+});++/** Running health is independent of install admission. Providers may continue with an+ * existing running Hub even when new installation is unsupported. */+export const setupHubRunning = (runtimeRead: RegionRead<RuntimeDependency>): boolean =>+ foldRegionRead(runtimeRead, {+ loading: () => false,+ unread: () => false,+ degraded: () => false,+ ready: (runtime) => runtime.enabled !== false && runtimeIsRunning(runtime),+ });++/** A necessary mode/runtime gate, NOT a complete readiness verdict. C4 additionally+ * requires the same candidate's route, credentials, application and permissions.+ * Setup always requires Hub; post-setup Direct choices belong to Settings. */+export const setupCandidateAllowed = (+ capability: SetupCapability,+ gatewayEnabled: boolean | null,+ runtimeRead: RegionRead<RuntimeDependency>,+ mode: 'direct' | 'hub' | undefined,+): boolean => setupNavigationReady(capability, gatewayEnabled) && mode === 'hub' && setupHubRunning(runtimeRead);++/** The screen a Back action leaves to, or `null` on the first one. */+export const setupBackTarget = (+ sequence: readonly SetupScreenId[],+ current: SetupScreenId,+): SetupScreenId | null => {+ const index = sequence.indexOf(current);+ return index > 0 ? sequence[index - 1] : null;+};