conversation-session-r3-uninstall.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import { runConfirmedProcess } from "#e2e/helpers/confirmed-process";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { resolve } from "node:path";
  4. import { buildServerRemoteWorkspaceIdentity } from "@zcode/shared";
  5. import {
  6. TID_SETTINGS_PAGE,
  7. TID_SETTINGS_BACK_BUTTON,
  8. TID_CONFIRM_DIALOG_CONFIRM,
  9. TID_SSH_ERROR,
  10. TID_SETTINGS_SECTION_NAV,
  11. TID_TASK_SETTINGS_BUTTON,
  12. testId,
  13. } from "@zcode/shared/test-ids";
  14. import {
  15. clearAppData,
  16. clickTestIdByDom,
  17. getE2EAppDataPaths,
  18. readSettings,
  19. } from "#e2e/helpers/desktop-app";
  20. import { getV4Messages, getV4ConversationState } from "#e2e/helpers/v4-conversation";
  21. import {
  22. prepareSSHLifecycle,
  23. connectSSHWorkspaceAndSendFirstTurn,
  24. type SSHLifecycleProvider,
  25. sendSSHFollowTurn,
  26. waitForRemoteWorkspaceDisconnected,
  27. } from "#e2e/helpers/ssh-remote-lifecycle";
  28. import {
  29. openWorkspaceDraftFromSidebar,
  30. selectTaskOrganizeMode,
  31. } from "#e2e/helpers/workspace-agent-warmup";
  32. import {
  33. clickLastEnabledSSHDialogButton,
  34. fillSSHPasswordSettings,
  35. openSSHRemoteDialog,
  36. openSSHSourceDirectory,
  37. readHostProcesses,
  38. readRemoteTabSnapshot,
  39. runSSHCommand,
  40. waitForSSHDirectoryStep,
  41. selectSSHRemoteDirectory,
  42. waitForRemoteTab,
  43. type SSHConnectionConfig,
  44. } from "#e2e/helpers/ssh-remote-p0";
  45. import { requestRemoteProjectConnection } from "#e2e/helpers/remote-project-actions";
  46. const CASE_MARKER = "E2E_R3_UNINSTALL";
  47. const variant = process.env.R3_UNINSTALL_CASE ?? "preserve-data";
  48. if (variant !== "preserve-data" && variant !== "replace-environment") {
  49. throw new Error(`Unsupported R3_UNINSTALL_CASE: ${variant}`);
  50. }
  51. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-uninstall");
  52. async function readInstallFacts(config: SSHConnectionConfig) {
  53. const result = await runSSHCommand(
  54. config,
  55. 'echo "installationId=$(grep -o \'"installationId": *"[^"]*"\' "$HOME/.zcode/server/install.json" 2>/dev/null | grep -oE "[0-9a-f-]{36}")"; ' +
  56. 'echo "current=$(test -f "$HOME/.zcode/server/current.json" && echo present || echo none)"; ' +
  57. 'echo "releases=$(ls "$HOME/.zcode/server/releases" 2>/dev/null | tr "\\n" ",")"; ' +
  58. 'echo "configSentinel=$(cat "$HOME/.zcode/server/config/e2e-sentinel.txt" 2>/dev/null || echo none)"; ' +
  59. 'echo "legacyAsset=$(test -e "$HOME/.zcode/server/e2e-legacy-asset.bin" && echo present || echo none)"; ' +
  60. 'echo "userData=$(cat "$HOME/.zcode/e2e-user-data.txt" 2>/dev/null || echo none)"; ' +
  61. 'echo "serverEntries=$(ls -A "$HOME/.zcode/server" 2>/dev/null | tr "\\n" ",")"; ' +
  62. 'echo "uninstalledMarker=$(cat "$HOME/.zcode/server/uninstalled.json" 2>/dev/null | tr -d "\\n ")"',
  63. );
  64. return Object.fromEntries(
  65. result.stdout
  66. .trim()
  67. .split("\n")
  68. .map((line) => {
  69. const index = line.indexOf("=");
  70. return [line.slice(0, index), line.slice(index + 1)];
  71. }),
  72. ) as Record<string, string>;
  73. }
  74. async function readVisibleTaskIds(identity: string): Promise<string[]> {
  75. await selectTaskOrganizeMode(["项目", "Project"]);
  76. const newProject = $(
  77. `[data-project-workspace-identity="${identity}"] [data-testid="virtual-project-toggle"]`,
  78. );
  79. if ((await newProject.getAttribute("aria-expanded")) !== "true") await newProject.click();
  80. let newTaskIds: string[] = [];
  81. await browser.waitUntil(
  82. async () => {
  83. const visible = await browser.execute((identity) => {
  84. const row = document.querySelector<HTMLElement>(
  85. `[data-project-workspace-identity="${identity}"]`,
  86. );
  87. // 新项目 section 自身包含任务列表;旧 li 祖先已不存在,不能因此把旧历史读成空列表。
  88. const taskIds = Array.from(
  89. row?.querySelectorAll<HTMLElement>('[data-testid^="task-item-"]') ?? [],
  90. ).map((item) => item.dataset.testid!.slice("task-item-".length));
  91. return { taskIds, empty: /暂无任务|No tasks/iu.test(row?.textContent ?? "") };
  92. }, identity);
  93. newTaskIds = visible.taskIds;
  94. return visible.empty || newTaskIds.length > 0;
  95. },
  96. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 项目任务列表未完成加载` },
  97. );
  98. return newTaskIds;
  99. }
  100. describe(`${CASE_MARKER}: ${variant},卸载重装与独立环境替换`, () => {
  101. const facts: Record<string, unknown> = { variant };
  102. let provider: SSHLifecycleProvider | null = null;
  103. after(async () => {
  104. await mkdir(artifactDir, { recursive: true });
  105. await writeFile(resolve(artifactDir, "uninstall.json"), JSON.stringify(facts, null, 2));
  106. await provider?.tunnel.close();
  107. await browser.electron.restoreAllMocks();
  108. await clearAppData();
  109. });
  110. it(`R3A-UPG-09 ${variant}: 卸载保留身份与历史;独立环境才确认新设备`, async function () {
  111. this.timeout(20 * 60_000);
  112. const prepared = await prepareSSHLifecycle(CASE_MARKER, { tunnelUsername: "tunnel" });
  113. provider = prepared.provider;
  114. const config = prepared.config;
  115. const workspaceA = config.workspacePaths[0];
  116. const initialHosts = await readHostProcesses();
  117. // 0911 修复:runner 每轮重建容器,全新目标没有 current.json——if 分支(正式
  118. // 卸载链路)永远进不去,错误落入为“容器复用上一轮卸载现场”设计的 else 分支,
  119. // uninstalledMarker 断言空串稳定 FAIL(r3-rerun §51 两次实录)。先经正式向导
  120. // 完成首装,满足“前置:已安装目标”,再放哨兵做卸载对账。
  121. const firstTab = await connectSSHWorkspaceAndSendFirstTurn({
  122. caseMarker: CASE_MARKER,
  123. config,
  124. provider,
  125. label: "A",
  126. workspacePath: workspaceA,
  127. });
  128. facts.originalTask = {
  129. taskId: firstTab.taskId,
  130. identity: firstTab.identity,
  131. prompt: firstTab.firstPrompt,
  132. };
  133. facts.firstSession = firstTab.remoteSessionId;
  134. const originalSettings = await readSettings();
  135. // 前置:已安装目标;放置 config 哨兵、旧散资产、用户数据哨兵。
  136. const seed = await runSSHCommand(
  137. config,
  138. 'mkdir -p "$HOME/.zcode/server/config" && echo R3_CONFIG_SENTINEL > "$HOME/.zcode/server/config/e2e-sentinel.txt" && ' +
  139. 'head -c 1024 /dev/zero > "$HOME/.zcode/server/e2e-legacy-asset.bin" && echo R3_USER_DATA > "$HOME/.zcode/e2e-user-data.txt" && echo ok',
  140. );
  141. expect(seed.stdout.trim()).toBe("ok");
  142. const before = await readInstallFacts(config);
  143. facts.before = before;
  144. const previousInstallationId = before.installationId;
  145. if (!previousInstallationId) throw new Error("首装没有安装身份");
  146. expect(previousInstallationId).toMatch(/^[0-9a-f-]{36}$/u);
  147. if (before.current === "present") {
  148. // 正式 CLI 卸载:收到每次确认提示后分别输入 DELETE,避免旧管道固定等待 33 秒。
  149. // 保留两次人工确认协议与 docker exec -i;不使用 --force 或直接删除目录代替卸载。
  150. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  151. if (!container) throw new Error(`${CASE_MARKER}: 缺少 ZCODE_E2E_SSH_CONTAINER`);
  152. const uninstallStarted = performance.now();
  153. const uninstall = await runConfirmedProcess(
  154. "docker",
  155. [
  156. "exec",
  157. "-i",
  158. "-u",
  159. "dev",
  160. container,
  161. "bash",
  162. "-lc",
  163. '"$HOME/.zcode/server/bin/zcode" uninstall --server-root "$HOME/.zcode/server" --json',
  164. ],
  165. {
  166. prompts: ["Type DELETE to uninstall ZCode Server: ", "Type DELETE again to confirm: "],
  167. answer: "DELETE",
  168. timeoutMs: 120_000,
  169. },
  170. );
  171. facts.uninstallDurationMs = Math.round(performance.now() - uninstallStarted);
  172. facts.uninstallOutput = uninstall.stdout.trim().split("\n").slice(-3);
  173. expect(uninstall.stdout).toContain('"uninstalled":true');
  174. expect(uninstall.stdout).toMatch(/"preservedPaths":\[[^\]]*"config"/u);
  175. } else {
  176. facts.uninstallOutput = "already uninstalled before this run (marker present)";
  177. expect(before.uninstalledMarker).toContain('"uninstalled":true');
  178. }
  179. const after = await readInstallFacts(config);
  180. facts.afterUninstall = after;
  181. // allowlist 只删运行资产:current/releases/run 消失;config 与其中哨兵原样保留;非 allowlist 的旧散资产与用户数据不动。
  182. expect(after.installationId).toBe(previousInstallationId);
  183. expect(after.current).toBe("none");
  184. expect(after.releases).toBe("");
  185. expect(after.configSentinel).toBe("R3_CONFIG_SENTINEL");
  186. expect(after.legacyAsset).toBe("present");
  187. expect(after.userData).toBe("R3_USER_DATA");
  188. expect(after.uninstalledMarker).toContain('"uninstalled":true');
  189. expect(after.uninstalledMarker).toContain("config");
  190. if (variant === "preserve-data") {
  191. await waitForRemoteWorkspaceDisconnected(firstTab.identity, CASE_MARKER);
  192. await requestRemoteProjectConnection(firstTab.identity, CASE_MARKER);
  193. // 原项目把未安装错误交接给向导,同时展示安装确认;先执行用户确认再等待连接结果。
  194. await (async () => {
  195. const button = $('[data-testid="ssh-dialog"]').$(
  196. './/button[normalize-space(.)="安装并继续" or normalize-space(.)="Install and continue"]',
  197. );
  198. await button.waitForClickable({
  199. timeout: 30_000,
  200. timeoutMsg: `${CASE_MARKER}: 原项目没有显示重新安装确认`,
  201. });
  202. await button.click();
  203. })().catch(async (cause: unknown) => {
  204. // 保留真实安装与 attachment 状态,区分缺少交接和意外静默重装,不能只记录向导超时。
  205. facts.reinstallFailure = {
  206. installation: await readInstallFacts(config),
  207. tab: await readRemoteTabSnapshot(firstTab.identity),
  208. ui: await browser.execute(
  209. (identity) => ({
  210. dialog: document.querySelector('[data-testid="ssh-dialog"]')?.textContent ?? null,
  211. projectState:
  212. document
  213. .querySelector(`[data-project-workspace-identity="${identity}"]`)
  214. ?.getAttribute("data-connection-state") ?? null,
  215. }),
  216. firstTab.identity,
  217. ),
  218. };
  219. throw cause;
  220. });
  221. facts.installConfirmationClicked = true;
  222. await $(`[data-testid="${TID_SSH_ERROR}"]`).waitForDisplayed({
  223. reverse: true,
  224. timeout: 30_000,
  225. });
  226. await waitForSSHDirectoryStep(CASE_MARKER);
  227. const restored = await waitForRemoteTab({
  228. caseMarker: CASE_MARKER,
  229. expectedIdentity: firstTab.identity,
  230. expectedPath: workspaceA,
  231. });
  232. expect(restored.remoteSessionId).toBeTruthy();
  233. expect(restored.remoteSessionId).not.toBe(firstTab.remoteSessionId);
  234. const installed = await readInstallFacts(config);
  235. expect(installed.installationId).toBe(previousInstallationId);
  236. expect(installed.current).toBe("present");
  237. expect(installed.configSentinel).toBe("R3_CONFIG_SENTINEL");
  238. expect(installed.userData).toBe("R3_USER_DATA");
  239. const settings = await readSettings();
  240. const profileIds = (value: typeof settings) =>
  241. value.connectionProfiles?.map((profile) => profile.profileId).sort();
  242. expect(profileIds(settings)).toEqual(profileIds(originalSettings));
  243. expect(settings.sourceServers?.map((source) => source.sourceServerId).sort()).toEqual(
  244. originalSettings.sourceServers?.map((source) => source.sourceServerId).sort(),
  245. );
  246. for (const original of originalSettings.connectionProfiles ?? []) {
  247. const current = settings.connectionProfiles?.find(
  248. (profile) => profile.profileId === original.profileId,
  249. );
  250. expect(current?.sourceServerId).toBe(original.sourceServerId);
  251. expect(current?.target).toEqual(original.target);
  252. expect(current?.lifecycleState).not.toBe("retired");
  253. }
  254. const projectKeys = (value: typeof settings) =>
  255. value.sourceServerWorkspaceHistory
  256. ?.map(({ sourceServerId, profileId, workspaceIdentity, workspacePath }) =>
  257. JSON.stringify({ sourceServerId, profileId, workspaceIdentity, workspacePath }),
  258. )
  259. .sort();
  260. expect(projectKeys(settings)).toEqual(projectKeys(originalSettings));
  261. const taskIds = await readVisibleTaskIds(firstTab.identity);
  262. expect(taskIds).toContain(firstTab.taskId);
  263. await sendSSHFollowTurn(
  264. { ...firstTab, remoteSessionId: restored.remoteSessionId! },
  265. CASE_MARKER,
  266. );
  267. expect((await getV4ConversationState()).taskId).toBe(firstTab.taskId);
  268. facts.preservedIdentity = {
  269. sourceServerId: installed.installationId,
  270. workspaceIdentity: restored.workspaceIdentity,
  271. profileIds: profileIds(settings),
  272. originalProjectKeys: projectKeys(originalSettings),
  273. restoredProjectKeys: projectKeys(settings),
  274. previousSession: firstTab.remoteSessionId,
  275. restoredSession: restored.remoteSessionId,
  276. taskIds,
  277. continuedTaskId: firstTab.taskId,
  278. };
  279. await browser.saveScreenshot(resolve(artifactDir, "preserved-history.png"));
  280. expect(await readHostProcesses()).toEqual(initialHosts);
  281. return;
  282. }
  283. // 身份变化只由真正独立的数据环境触发。完整封存旧数据,不能只删 UUID 却共享历史库。
  284. const replaced = await runSSHCommand(
  285. config,
  286. 'test ! -e "$HOME/r3-uninstall-preserved-data" && mv "$HOME/.zcode" "$HOME/r3-uninstall-preserved-data"',
  287. );
  288. expect(replaced.code).toBe(0);
  289. facts.originalDataArchived = true;
  290. // 同一线路安装到空环境,检测到不同身份后必须等待确认;取消不改绑原连接。
  291. await openWorkspaceDraftFromSidebar(resolve(getE2EAppDataPaths().homeDir, "ZCodeProject"));
  292. await openSSHRemoteDialog(CASE_MARKER);
  293. await fillSSHPasswordSettings(config);
  294. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  295. let identityError = "";
  296. try {
  297. await waitForSSHDirectoryStep(CASE_MARKER);
  298. } catch (error) {
  299. identityError = String(error);
  300. }
  301. facts.reconnectFirstAttempt = identityError.slice(0, 200);
  302. if (!/身份换代|身份已变化|identity has changed/iu.test(identityError)) {
  303. throw new Error(
  304. `${CASE_MARKER}: 首连预期报身份换代错误,实际: ${identityError || "(成功,与独立环境状态矛盾)"}`,
  305. );
  306. }
  307. // 关闭报错向导,进入设置>远程设备确认换代。
  308. await browser.waitUntil(
  309. () =>
  310. browser.execute(() => {
  311. const close = Array.from(
  312. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  313. ).find(
  314. (button) =>
  315. button.getClientRects().length &&
  316. !button.disabled &&
  317. ["关闭", "Close"].includes(button.innerText.trim()),
  318. );
  319. close?.click();
  320. return Boolean(close);
  321. }),
  322. { timeout: 30_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 报错向导没有关闭按钮` },
  323. );
  324. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  325. // 身份确认属于设置连接流程;关闭错误页后仍在设置,不能点击被它遮挡的全局入口。
  326. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed())) {
  327. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  328. timeout: 15_000,
  329. timeoutMsg: `${CASE_MARKER}: 没有设置入口`,
  330. });
  331. }
  332. await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).waitForDisplayed({ timeout: 15_000 });
  333. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"), {
  334. timeout: 15_000,
  335. timeoutMsg: `${CASE_MARKER}: 设置页没有远程设备分区`,
  336. });
  337. // 身份变化必须经用户确认;重装按钮不能替代确认,更不能删除设备绕过身份边界。
  338. const pendingSettings = await readSettings();
  339. const oldProfile = pendingSettings.connectionProfiles?.find(
  340. (profile) =>
  341. profile.sourceServerId === previousInstallationId && profile.lifecycleState !== "retired",
  342. );
  343. expect(oldProfile).toBeDefined();
  344. const clickIdentityConfirmation = async () => {
  345. await browser.waitUntil(
  346. () =>
  347. browser.execute((sourceId) => {
  348. // 安装身份才是设备卡的稳定定位;线路地址文本会随当前/默认连接展示改变。
  349. const card = document.querySelector(`[data-source-server-card="${sourceId}"]`);
  350. const button = Array.from(card?.querySelectorAll("button") ?? []).find(
  351. (node) =>
  352. node.getClientRects().length &&
  353. !node.disabled &&
  354. node.innerText.trim() === "作为新设备使用",
  355. );
  356. button?.click();
  357. return Boolean(button);
  358. }, previousInstallationId),
  359. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 身份换代待确认,但设备卡没有可用确认入口` },
  360. );
  361. await $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).waitForDisplayed({
  362. timeout: 15_000,
  363. });
  364. };
  365. try {
  366. await clickIdentityConfirmation();
  367. await browser.saveScreenshot(resolve(artifactDir, "identity-confirmation.png"));
  368. // 取消必须保留原绑定;不能在打开确认框时就提交身份替换。
  369. await browser.keys(["Escape"]);
  370. await $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).waitForDisplayed({
  371. reverse: true,
  372. timeout: 15_000,
  373. });
  374. expect((await readSettings()).connectionProfiles).toEqual(pendingSettings.connectionProfiles);
  375. facts.cancelPreservedOriginalProfiles = true;
  376. await clickIdentityConfirmation();
  377. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  378. await browser.waitUntil(
  379. async () => {
  380. const settings = await readSettings();
  381. return (
  382. settings.connectionProfiles?.some(
  383. (profile) =>
  384. profile.profileId === oldProfile!.profileId && profile.lifecycleState === "retired",
  385. ) ?? false
  386. );
  387. },
  388. { timeout: 60_000, timeoutMsg: `${CASE_MARKER}: 确认后旧线路没有按身份替换合同归档` },
  389. );
  390. const installed = await readInstallFacts(config);
  391. const settings = await readSettings();
  392. const replacement = settings.connectionProfiles?.find(
  393. (profile) =>
  394. profile.sourceServerId === installed.installationId &&
  395. profile.lifecycleState !== "retired",
  396. );
  397. expect(replacement).toBeDefined();
  398. expect(replacement!.profileId).not.toBe(oldProfile!.profileId);
  399. expect(installed.installationId).not.toBe(previousInstallationId);
  400. expect(
  401. settings.sourceServers?.some((server) => server.sourceServerId === previousInstallationId),
  402. ).toBe(true);
  403. expect(
  404. settings.sourceServerWorkspaceHistory?.filter(
  405. (entry) => entry.sourceServerId === previousInstallationId,
  406. ),
  407. ).toEqual(
  408. pendingSettings.sourceServerWorkspaceHistory?.filter(
  409. (entry) => entry.sourceServerId === previousInstallationId,
  410. ),
  411. );
  412. facts.identityConfirmed = {
  413. oldSource: previousInstallationId,
  414. newSource: installed.installationId,
  415. oldProfileRetired: true,
  416. replacementProfileCreated: true,
  417. oldHistoryPreserved: true,
  418. };
  419. } catch (error) {
  420. facts.identityConfirmationFailure = {
  421. message: String(error),
  422. settingsPanelText: await browser.execute(
  423. () =>
  424. document.querySelector<HTMLElement>('[data-testid="settings-page"]')?.innerText ??
  425. "absent",
  426. ),
  427. installation: await readInstallFacts(config),
  428. };
  429. throw error;
  430. }
  431. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  432. // 旧 helper 进入空的新建连接表单,无法找到已保存设备;复用项目设备选择并排除已归档线路。
  433. const newInstallation = await readInstallFacts(config);
  434. await openSSHSourceDirectory(config, CASE_MARKER);
  435. await waitForSSHDirectoryStep(CASE_MARKER);
  436. await selectSSHRemoteDirectory(workspaceA, CASE_MARKER);
  437. const reconnectedTab = await waitForRemoteTab({
  438. caseMarker: CASE_MARKER,
  439. expectedPath: workspaceA,
  440. expectedIdentity: buildServerRemoteWorkspaceIdentity({
  441. serverId: newInstallation.installationId!,
  442. workspacePath: workspaceA,
  443. }),
  444. });
  445. facts.reconnectedSession = {
  446. before: firstTab.remoteSessionId,
  447. after: reconnectedTab.remoteSessionId,
  448. };
  449. expect(reconnectedTab.remoteSessionId).toBeTruthy();
  450. expect(reconnectedTab.remoteSessionId).not.toBe(firstTab.remoteSessionId);
  451. const reinstalled = await readInstallFacts(config);
  452. facts.afterReinstall = reinstalled;
  453. expect(reinstalled.current).toBe("present");
  454. expect(reinstalled.installationId).toMatch(/[0-9a-f-]{36}/u);
  455. expect(reinstalled.installationId).not.toBe(previousInstallationId);
  456. facts.installationIdChanged = reinstalled.installationId !== previousInstallationId;
  457. expect(reinstalled.configSentinel).toBe("none");
  458. expect(reinstalled.userData).toBe("none");
  459. // 真实旧任务保留在封存的数据环境;新环境不能因目录相同而得到旧历史。
  460. const runtime = JSON.parse(
  461. (await runSSHCommand(config, 'cat "$HOME/.zcode/server/current.json"')).stdout,
  462. );
  463. const history = await runSSHCommand(
  464. config,
  465. `'${runtime.releaseDir}/runtime/node' --input-type=module -e 'import {DatabaseSync} from "node:sqlite";const db=new DatabaseSync(process.env.HOME+"/r3-uninstall-preserved-data/v2/tasks-index.sqlite");const rows=db.prepare("SELECT workspace_key FROM tasks WHERE task_id=?").all(process.argv[1]);db.close();process.stdout.write(JSON.stringify(rows));' '${firstTab.taskId}'`,
  466. );
  467. expect(history.code).toBe(0);
  468. const oldRows = JSON.parse(history.stdout) as Array<{ workspace_key: string }>;
  469. expect(oldRows.length).toBeGreaterThan(0);
  470. // Server 保留 legacy canonical key 以支持回退;安装 UUID 是 App 设备身份,不能拿它断言内部存储格式。
  471. facts.preservedTaskStorageRows = oldRows;
  472. const newTaskIds = await readVisibleTaskIds(reconnectedTab.workspaceIdentity!);
  473. facts.newInstallationTaskIds = newTaskIds;
  474. expect(newTaskIds).not.toContain(firstTab.taskId);
  475. expect((await getV4ConversationState()).taskId).not.toBe(firstTab.taskId);
  476. expect(
  477. (await getV4Messages("user")).some((message) => message.text?.includes(firstTab.firstPrompt)),
  478. ).toBe(false);
  479. facts.oldHistoryPreservedOutsideNewEnvironment = true;
  480. await browser.saveScreenshot(resolve(artifactDir, "new-environment-empty.png"));
  481. expect(await readHostProcesses()).toEqual(initialHosts);
  482. });
  483. });