conversation-session-r3-bot-private-client-id.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { isBotInputClientId, type BotInboundMessage } from "@zcode/shared";
  4. import { createFeishuConfig } from "#e2e/bots/helpers/bots-service-harness";
  5. import { clearAppData } from "#e2e/helpers/desktop-app";
  6. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  7. import {
  8. getUpstreamRequestRecordCount,
  9. waitForUpstreamRequest,
  10. } from "#e2e/helpers/conversation-session-network";
  11. import {
  12. connectSSHWorkspaceAndSendFirstTurn,
  13. prepareSSHLifecycle,
  14. type SSHLifecycleProvider,
  15. } from "#e2e/helpers/ssh-remote-lifecycle";
  16. import { runSSHCommand } from "#e2e/helpers/ssh-remote-p0";
  17. import { waitForV4ConversationState } from "#e2e/helpers/v4-conversation";
  18. // Bot 私聊输入的命令信封 clientId 是 `bot:<botId>:<chatId>:<userId>`(formatBotInputClientId)。私聊过去用
  19. // host-services-*,远端 workspace 下要确认 Source Server 侧不会按 terminal-client 的 clientId 一致性检查
  20. // (zcodeAgentConnectionScope fault.command.clientMismatch)拒掉它:Telegram 私聊经真实 Host Bot 服务投到
  21. // 远端任务,远端 CLI 必须真的跑这一轮(上游回放收到请求),且远端会话账本记下的 clientId 是 bot 形状。
  22. const CASE_MARKER = "E2E_R3_BOT_PRIVATE";
  23. const SEND_MARKER = `${CASE_MARKER}_TELEGRAM`;
  24. const artifactDir = resolve(
  25. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-bot-private-client-id",
  26. );
  27. describe(`${CASE_MARKER}: Telegram 私聊输入投到远端 workspace 不被 clientId 检查拒绝`, () => {
  28. let provider: SSHLifecycleProvider | null = null;
  29. const facts: Record<string, unknown> = {};
  30. after(async () => {
  31. await mkdir(artifactDir, { recursive: true });
  32. await writeFile(resolve(artifactDir, "bot-private.json"), JSON.stringify(facts, null, 2));
  33. await provider?.tunnel.close().catch(() => undefined);
  34. provider = null;
  35. await browser.electron.restoreAllMocks();
  36. await clearAppData();
  37. });
  38. it("Telegram 私聊经 Host Bot 服务投到远端任务,远端 CLI 执行该轮", async function () {
  39. this.timeout(25 * 60_000);
  40. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  41. apiType: "anthropic-messages",
  42. tunnelUsername: "tunnel",
  43. });
  44. provider = prepared.provider;
  45. const [workspaceA] = prepared.config.workspacePaths;
  46. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  47. caseMarker: CASE_MARKER,
  48. config: prepared.config,
  49. label: "A",
  50. provider,
  51. workspacePath: workspaceA,
  52. });
  53. await waitForV4ConversationState(
  54. (s) => s.taskId === taskA.taskId && s.state === "idle",
  55. `${CASE_MARKER}: 首轮没有收口`,
  56. 90_000,
  57. );
  58. // 只经真实 Host Bot 服务输入;不配凭据,不向 Telegram 发网络请求。
  59. const botId = "telegram-r3-e2e";
  60. const config = createFeishuConfig("feishu", botId);
  61. const bot = config.bots[0]!;
  62. delete bot.credentialRef;
  63. delete (bot as { feishuAppId?: string }).feishuAppId;
  64. config.bots = [{ ...bot, provider: "telegram", replyMode: "assistant_changes" }];
  65. const root = join(resolveE2EStorageRoot(), "v2");
  66. await mkdir(root, { recursive: true });
  67. await writeFile(join(root, "bot-config.v3.json"), JSON.stringify(config));
  68. await writeFile(
  69. join(root, "bot-state.v3.json"),
  70. JSON.stringify({
  71. version: 3,
  72. bots: {
  73. [botId]: {
  74. botId,
  75. workspacePath: taskA.workspacePath,
  76. workspaceIdentity: taskA.identity,
  77. workspaceId: taskA.identity,
  78. mode: "task",
  79. activeTaskId: taskA.taskId,
  80. updatedAt: Date.now(),
  81. },
  82. },
  83. }),
  84. );
  85. const requestStart = await getUpstreamRequestRecordCount();
  86. const message: BotInboundMessage = {
  87. botId,
  88. text: `${SEND_MARKER}: 只回复 R3_BOT_PRIVATE_REPLY`,
  89. actor: {
  90. botId,
  91. provider: "telegram",
  92. chatType: "private",
  93. chatId: "tg-chat-e2e",
  94. providerUserId: bot.providerUserId!,
  95. providerMessageId: "tg-message-e2e",
  96. },
  97. };
  98. // __testActions 走当前激活 workspace 的服务;Bot 由本机 Host 承载(远端项目经 remoteWorkspaceService
  99. // 拿远端 taskService),所以先切回本地 tab,让输入进本机 Host 的 Bot 服务。
  100. const switched = await browser.execute(() => {
  101. const store = (
  102. window as Window & {
  103. __zcodeTabStoreE2E?: {
  104. getState?: () => {
  105. tabs?: Array<{ id: string; workspaceIdentity?: string }>;
  106. activateTab?: (tabId: string) => void;
  107. };
  108. };
  109. }
  110. ).__zcodeTabStoreE2E;
  111. const state = store?.getState?.();
  112. const local = state?.tabs?.find((tab) => !tab.workspaceIdentity);
  113. if (!local || !state?.activateTab) return false;
  114. state.activateTab(local.id);
  115. return true;
  116. });
  117. facts.switchedToLocalTab = switched;
  118. expect(switched).toBe(true);
  119. await browser.pause(1_500);
  120. const reply = await browser.execute(async (input) => {
  121. return (
  122. window as unknown as {
  123. __testActions: { sendBotMessage(input: BotInboundMessage): Promise<unknown> };
  124. }
  125. ).__testActions.sendBotMessage(input);
  126. }, message);
  127. facts.reply = reply;
  128. await waitForUpstreamRequest(
  129. { lastUserMessageIncludes: [SEND_MARKER] },
  130. `${CASE_MARKER}: Telegram 私聊输入没有在远端执行(可能被 clientId 检查拒绝)`,
  131. 120_000,
  132. { afterIndex: requestStart - 1 },
  133. );
  134. facts.remoteTurnReachedUpstream = true;
  135. // 远端 CLI 输入账本里这一轮的 clientId 是 bot 形状:证明命令以 bot: clientId 进入远端并被接纳。
  136. const ledger = await runSSHCommand(
  137. prepared.config,
  138. `grep -rao '"clientId":"bot:[^"]*"' "$HOME/.zcode/cli/db" 2>/dev/null | head -n 5`,
  139. );
  140. const clientIds = [...ledger.stdout.matchAll(/"clientId":"([^"]+)"/gu)].map((m) => m[1]!);
  141. facts.remoteClientIds = clientIds;
  142. expect(clientIds.some((id) => isBotInputClientId(id) && id.includes(botId))).toBe(true);
  143. });
  144. });