control.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createCliSessionControl } from "#session-control/application/cli/index";
  3. import { createAppSessionControl } from "#session-control/application/app/index";
  4. import { createTestPorts } from "#session-control/testing/index";
  5. import {
  6. appListProjectsInputSchema,
  7. appListSessionsInputSchema,
  8. cliCreateSessionInputSchema,
  9. type AppScope,
  10. type AppSessionRef,
  11. type CliSessionRef,
  12. } from "#session-control/contract";
  13. const cliRoot: CliSessionRef = { kind: "cli", workspacePath: "/workspace", sessionId: "sess_root" };
  14. const cliTarget: CliSessionRef = { ...cliRoot, sessionId: "sess_target" };
  15. const appRoot: AppSessionRef = {
  16. kind: "app",
  17. workspacePath: "/workspace",
  18. sourceServerId: "source-a",
  19. sessionId: "sess_root",
  20. };
  21. const appTarget: AppSessionRef = { ...appRoot, sessionId: "sess_target" };
  22. function cliFixture() {
  23. const ports = createTestPorts("cli", cliRoot);
  24. return { ports, ctx: ports.context, control: createCliSessionControl(ports.cli) };
  25. }
  26. function appFixture() {
  27. const ports = createTestPorts("app", appRoot);
  28. return { ports, ctx: ports.context, control: createAppSessionControl(ports.app) };
  29. }
  30. describe("strict schemas and independent facades", () => {
  31. it("has only the eight CLI and twelve App application actions", () => {
  32. const { control } = cliFixture();
  33. expect(Object.keys(control).sort()).toEqual([
  34. "createSession",
  35. "forkSession",
  36. "interruptSession",
  37. "listSessions",
  38. "readSession",
  39. "renameSession",
  40. "sendToSession",
  41. "waitSessions",
  42. ]);
  43. expect(Object.keys(appFixture().control)).toHaveLength(12);
  44. });
  45. it("rejects unknown fields, blank input and spoofed context", async () => {
  46. const { control, ctx, ports } = cliFixture();
  47. // 规格 0.14:cwd 已从契约删除,多传即被 strictObject 拒。
  48. expect(
  49. cliCreateSessionInputSchema.safeParse({ cwd: "/workspace", prompt: "run", requestId: "r" })
  50. .success,
  51. ).toBe(false);
  52. expect(cliCreateSessionInputSchema.safeParse({ prompt: "run", requestId: "r" }).success).toBe(
  53. true,
  54. );
  55. await expect(
  56. control.sendToSession(ctx, {
  57. session: cliTarget,
  58. prompt: "run",
  59. requestId: "r",
  60. callerId: "spoof",
  61. } as never),
  62. ).rejects.toMatchObject({ code: "invalid_input" });
  63. await expect(
  64. control.sendToSession(ctx, { session: cliTarget, prompt: " ", requestId: "r" }),
  65. ).rejects.toMatchObject({ code: "invalid_input" });
  66. expect(ports.calls).toEqual([]);
  67. });
  68. it("rejects kind, workspace and source crossings before owner calls", async () => {
  69. const { control, ctx, ports } = appFixture();
  70. await expect(
  71. control.readSession(ctx, { session: cliTarget as never, view: "summary" }),
  72. ).rejects.toMatchObject({ code: "invalid_input" });
  73. for (const session of [
  74. { ...appTarget, workspacePath: "/other" },
  75. { ...appTarget, sourceServerId: "source-b" },
  76. ]) {
  77. await expect(control.readSession(ctx, { session, view: "summary" })).rejects.toMatchObject({
  78. code: "forbidden",
  79. });
  80. }
  81. expect(ports.calls).toEqual([]);
  82. });
  83. it("checks access grants and output schema instead of trusting adapter types", async () => {
  84. const { control, ctx, ports } = cliFixture();
  85. ports.cli.access.authorize = async () => ({
  86. scope: { kind: "cli", workspacePath: "/other" },
  87. fence: "epoch",
  88. });
  89. await expect(
  90. control.readSession(ctx, { session: cliTarget, view: "summary" }),
  91. ).rejects.toMatchObject({ code: "forbidden" });
  92. const other = cliFixture();
  93. other.ports.cli.execution.sendToSession = async () =>
  94. ({
  95. session: cliTarget,
  96. operation: { session: cliTarget, sessionId: cliTarget.sessionId, commandId: "r" },
  97. admission: "accepted",
  98. delivery: "queued",
  99. unexpected: true,
  100. }) as never;
  101. await expect(
  102. other.control.sendToSession(other.ctx, { session: cliTarget, prompt: "go", requestId: "r" }),
  103. ).rejects.toMatchObject({ code: "invalid_output" });
  104. });
  105. it("rejects wrong-session receipts and cross-scope list output", async () => {
  106. const { control, ctx, ports } = cliFixture();
  107. ports.cli.execution.sendToSession = async () => ({
  108. requestId: "r",
  109. session: cliRoot,
  110. operation: { session: cliRoot, sessionId: cliRoot.sessionId, commandId: "r" },
  111. admission: "accepted",
  112. delivery: "queued",
  113. });
  114. await expect(
  115. control.sendToSession(ctx, { session: cliTarget, prompt: "go", requestId: "r" }),
  116. ).rejects.toMatchObject({ code: "invalid_output" });
  117. ports.cli.sessions.listSessions = async () => ({
  118. sessions: [
  119. {
  120. session: { ...cliTarget, workspacePath: "/other" },
  121. title: "private",
  122. status: "idle",
  123. availableActions: [],
  124. },
  125. ],
  126. });
  127. await expect(control.listSessions(ctx, {})).rejects.toMatchObject({ code: "invalid_output" });
  128. });
  129. });
  130. describe("CLI owner boundary", () => {
  131. it("preserves trace fields and keeps different workspace identities isolated", async () => {
  132. const { control, ctx, ports } = cliFixture();
  133. const traced = { ...ctx, traceId: "trace-1", turnId: "turn-1", toolCallId: "tool-1" };
  134. await control.renameSession(traced, {
  135. session: cliTarget,
  136. title: "Renamed",
  137. requestId: "rename",
  138. });
  139. expect(ports.calls.at(-1)?.ctx).toBe(traced);
  140. await expect(
  141. control.readSession(ctx, {
  142. session: { ...cliTarget, workspaceIdentity: "other-identity" },
  143. view: "summary",
  144. }),
  145. ).rejects.toMatchObject({ code: "forbidden" });
  146. });
  147. it("passes stable identity and fence without retries or another admission queue", async () => {
  148. const { control, ctx, ports } = cliFixture();
  149. const input = { session: cliTarget, prompt: "go", requestId: "stable-request" };
  150. const result = await control.sendToSession(ctx, input);
  151. expect(result.admission).toBe("accepted");
  152. expect(result.delivery).toBe("queued");
  153. expect(ports.calls.map((call) => call.method)).toEqual(["authorize", "sendToSession"]);
  154. expect(ports.calls[1]).toMatchObject({ ctx, input, grant: { fence: "test-epoch" } });
  155. ports.cli.execution.sendToSession = vi.fn(async () => {
  156. throw new Error("owner unknown");
  157. });
  158. await expect(control.sendToSession(ctx, input)).rejects.toThrow("owner unknown");
  159. expect(ports.cli.execution.sendToSession).toHaveBeenCalledTimes(1);
  160. });
  161. it("keeps partial create results and never retries rejected first input", async () => {
  162. const { control, ctx, ports } = cliFixture();
  163. ports.cli.execution.createSession = async () => ({
  164. requestId: "r",
  165. creation: "created",
  166. firstInput: "rejected",
  167. delivery: "none",
  168. session: cliTarget,
  169. reason: "provider unavailable",
  170. });
  171. await expect(
  172. control.createSession(ctx, { prompt: "go", requestId: "r" }),
  173. ).resolves.toMatchObject({ creation: "created", firstInput: "rejected" });
  174. expect(ports.calls.map((call) => call.method)).toEqual(["authorize"]);
  175. });
  176. it("defaults lists to the trusted root workspace, and forwards explicit execution guards", async () => {
  177. const { control, ctx, ports } = cliFixture();
  178. await control.listSessions(ctx, {});
  179. expect(ports.calls[1]?.input).toMatchObject({
  180. workspace: { kind: "cli", workspacePath: "/workspace" },
  181. });
  182. await control.interruptSession(ctx, {
  183. session: cliTarget,
  184. expectedExecutionId: "execution-2",
  185. requestId: "stop",
  186. });
  187. expect(ports.calls.at(-1)?.input).toMatchObject({
  188. expectedExecutionId: "execution-2",
  189. requestId: "stop",
  190. });
  191. });
  192. it("forks without automatically sending and preserves the stable history point", async () => {
  193. const { control, ctx, ports } = cliFixture();
  194. await control.forkSession(ctx, {
  195. session: cliTarget,
  196. atMessage: "message-5",
  197. requestId: "fork",
  198. });
  199. expect(ports.calls.map((call) => call.method)).toEqual(["authorize", "forkSession"]);
  200. expect(ports.calls.at(-1)?.input).toMatchObject({ atMessage: "message-5" });
  201. });
  202. });
  203. describe("App side effect boundaries", () => {
  204. it("defaults to discovery across projects and sources even when the root is unclassified", async () => {
  205. const { control, ctx, ports } = appFixture();
  206. const discoveryScopes: AppScope[] = [
  207. { kind: "app", scope: "host", sourceServerId: "source-a" },
  208. { kind: "app", scope: "project", projectId: "remote", sourceServerId: "source-b" },
  209. ];
  210. const discovery = { ...ctx, rootSession: appRoot, discoveryScopes };
  211. const sessions = [
  212. {
  213. ...appTarget,
  214. project: { kind: "app" as const, projectId: "novel", sourceServerId: "source-a" },
  215. },
  216. {
  217. ...appTarget,
  218. sourceServerId: "source-b",
  219. project: { kind: "app" as const, projectId: "remote", sourceServerId: "source-b" },
  220. },
  221. appTarget,
  222. ].map((session) => ({
  223. session,
  224. title: "2000字小说创作",
  225. status: "idle" as const,
  226. availableActions: [],
  227. }));
  228. const result = { sessions, searchScope: { scopes: discoveryScopes, unavailableSources: [] } };
  229. const listSessions = vi.fn(async () => result);
  230. ports.app.sessions.listSessions = listSessions;
  231. await expect(control.listSessions(discovery, { query: "小说" })).resolves.toEqual(result);
  232. expect(listSessions).toHaveBeenCalledWith(
  233. discovery,
  234. { query: "小说", archived: "exclude" },
  235. discoveryScopes.map((scope) => ({ scope, fence: "test-epoch" })),
  236. );
  237. expect(ports.calls.every((call) => call.ctx === discovery)).toBe(true);
  238. expect(discovery.allowedScopes).toBe(ctx.allowedScopes);
  239. const projects = sessions.flatMap(({ session }) =>
  240. session.project ? [{ project: session.project, title: "小说项目" }] : [],
  241. );
  242. ports.app.projects.listProjects = vi.fn(async () => ({
  243. projects,
  244. searchScope: result.searchScope,
  245. }));
  246. await expect(control.listProjects(discovery, {})).resolves.toEqual({
  247. projects,
  248. searchScope: result.searchScope,
  249. });
  250. expect(ports.app.projects.listProjects).toHaveBeenCalledWith(
  251. discovery,
  252. {},
  253. discoveryScopes.map((scope) => ({ scope, fence: "test-epoch" })),
  254. );
  255. });
  256. it("falls back to existing grants without injecting a root project or workspace", async () => {
  257. const { control, ctx, ports } = appFixture();
  258. await expect(control.listSessions(ctx, {})).resolves.toEqual({
  259. sessions: [],
  260. searchScope: { scopes: ctx.allowedScopes, unavailableSources: [] },
  261. });
  262. expect(ports.calls.at(-1)?.input).toEqual({ archived: "exclude" });
  263. expect(ports.calls.at(-1)?.grant).toEqual(
  264. ctx.allowedScopes.map((scope) => ({ scope, fence: "test-epoch" })),
  265. );
  266. await control.listSessions({ ...ctx, rootSession: appRoot }, {});
  267. expect(ports.calls.at(-1)?.input).toEqual({ archived: "exclude" });
  268. });
  269. it("does not fall back to operation permissions when discovery is explicitly empty", async () => {
  270. const { control, ctx, ports } = appFixture();
  271. const discovery = { ...ctx, discoveryScopes: [] };
  272. await expect(control.listSessions(discovery, {})).resolves.toEqual({
  273. sessions: [],
  274. searchScope: { scopes: [], unavailableSources: [] },
  275. });
  276. await expect(control.listProjects(discovery, {})).resolves.toEqual({
  277. projects: [],
  278. searchScope: { scopes: [], unavailableSources: [] },
  279. });
  280. expect(ports.calls.some((call) => call.method === "authorize")).toBe(false);
  281. await expect(
  282. control.listSessions(discovery, { project: ctx.rootSession.project }),
  283. ).rejects.toMatchObject({ code: "forbidden" });
  284. });
  285. it("narrows explicit project, workspace and host filters without changing the caller context", async () => {
  286. const { control, ctx, ports } = appFixture();
  287. const discovery = {
  288. ...ctx,
  289. discoveryScopes: [{ kind: "app", scope: "host", sourceServerId: "source-a" }] as AppScope[],
  290. };
  291. const project = {
  292. kind: "app" as const,
  293. projectId: "other-project",
  294. sourceServerId: "source-a",
  295. };
  296. await control.listSessions(discovery, { project });
  297. expect(ports.calls.at(-1)).toMatchObject({
  298. ctx: discovery,
  299. input: { project, archived: "exclude" },
  300. grant: [{ scope: { ...project, scope: "project" }, fence: "test-epoch" }],
  301. });
  302. const workspace = {
  303. kind: "app" as const,
  304. workspacePath: "/other-workspace",
  305. sourceServerId: "source-a",
  306. };
  307. // 规格 0.14:workspace 过滤器已从契约删除(发现链循环),多传即被 strictObject 拒。
  308. expect(appListSessionsInputSchema.safeParse({ workspace }).success).toBe(false);
  309. const callsBeforeForbidden = ports.calls.length;
  310. await expect(
  311. control.listSessions(discovery, { project: { ...project, sourceServerId: "source-b" } }),
  312. ).rejects.toMatchObject({ code: "forbidden" });
  313. // 规格 0.14:host 过滤器已删除,发现范围恒为可信上下文授予的全部来源。
  314. expect(appListProjectsInputSchema.safeParse({ host: "source-b" }).success).toBe(false);
  315. expect(ports.calls).toHaveLength(callsBeforeForbidden);
  316. });
  317. it("rejects project rows and other identities in an explicit unclassified workspace result", async () => {
  318. const { control, ctx, ports } = appFixture();
  319. const workspace = {
  320. kind: "app" as const,
  321. workspacePath: "/workspace",
  322. sourceServerId: "source-a",
  323. };
  324. const discovery = {
  325. ...ctx,
  326. discoveryScopes: [{ kind: "app", scope: "host", sourceServerId: "source-a" }] as AppScope[],
  327. };
  328. const searchScope = {
  329. scopes: [{ ...workspace, scope: "workspace" as const }],
  330. unavailableSources: [],
  331. };
  332. for (const session of [
  333. { ...appTarget, project: ctx.rootSession.project },
  334. { ...appTarget, workspaceIdentity: "other-workspace" },
  335. { ...appTarget, sourceServerId: "source-b" },
  336. ]) {
  337. ports.app.sessions.listSessions = async () => ({
  338. sessions: [{ session, title: "hidden", status: "idle", availableActions: [] }],
  339. searchScope,
  340. });
  341. // 不再有显式 workspace 过滤;输出复验仍按回执声明的搜索范围拒绝越界行。
  342. await expect(control.listSessions(discovery, {})).rejects.toMatchObject({
  343. code: "invalid_output",
  344. });
  345. }
  346. ports.app.sessions.listSessions = async () => ({
  347. sessions: [
  348. { session: appTarget, title: "unclassified", status: "idle", availableActions: [] },
  349. ],
  350. searchScope,
  351. });
  352. await expect(control.listSessions(discovery, {})).resolves.toMatchObject({
  353. sessions: [{ session: appTarget }],
  354. });
  355. });
  356. it("rejects wrong source, project or inconsistent project source from a discovered project", async () => {
  357. const { control, ctx, ports } = appFixture();
  358. const project = ctx.rootSession.project!;
  359. const scope: AppScope = { ...project, scope: "project" };
  360. const searchScope = { scopes: [scope], unavailableSources: [] };
  361. for (const session of [
  362. { ...appTarget, project: { ...project, projectId: "forbidden" } },
  363. { ...appTarget, sourceServerId: "source-b", project },
  364. { ...appTarget, project: { ...project, sourceServerId: "source-b" } },
  365. appTarget,
  366. ]) {
  367. ports.app.sessions.listSessions = async () => ({
  368. sessions: [{ session, title: "hidden", status: "idle", availableActions: [] }],
  369. searchScope,
  370. });
  371. await expect(
  372. control.listSessions({ ...ctx, discoveryScopes: [scope] }, {}),
  373. ).rejects.toMatchObject({ code: "invalid_output" });
  374. await expect(
  375. control.listSessions(
  376. { ...ctx, discoveryScopes: [{ kind: "app", scope: "host", sourceServerId: "source-a" }] },
  377. { project },
  378. ),
  379. ).rejects.toMatchObject({ code: "invalid_output" });
  380. }
  381. });
  382. it("keeps discovered sessions outside operation grants forbidden for read and send", async () => {
  383. const { control, ctx, ports } = appFixture();
  384. const discovery = {
  385. ...ctx,
  386. allowedScopes: [{ ...ctx.rootSession.project!, scope: "project" as const }],
  387. discoveryScopes: [{ kind: "app", scope: "host", sourceServerId: "source-a" }] as AppScope[],
  388. };
  389. const session = {
  390. ...appTarget,
  391. project: { ...ctx.rootSession.project!, projectId: "other-project" },
  392. };
  393. ports.app.sessions.listSessions = async () => ({
  394. sessions: [{ session, title: "2000字小说创作", status: "idle", availableActions: [] }],
  395. searchScope: { scopes: discovery.discoveryScopes, unavailableSources: [] },
  396. });
  397. const result = await control.listSessions(discovery, {});
  398. const returned = result.sessions[0]!.session;
  399. const callsAfterDiscovery = ports.calls.length;
  400. await expect(
  401. control.readSession(discovery, { session: returned, view: "messages" }),
  402. ).rejects.toMatchObject({ code: "forbidden" });
  403. await expect(
  404. control.sendToSession(discovery, { session: returned, prompt: "go", requestId: "denied" }),
  405. ).rejects.toMatchObject({ code: "forbidden" });
  406. expect(ports.calls).toHaveLength(callsAfterDiscovery);
  407. });
  408. it("preserves successful subscopes and reports unavailable sources as partial coverage", async () => {
  409. const { control, ctx, ports } = appFixture();
  410. const discoveryScopes: AppScope[] = [
  411. { kind: "app", scope: "host", sourceServerId: "source-a" },
  412. { kind: "app", scope: "host", sourceServerId: "source-b" },
  413. ];
  414. const project = ctx.rootSession.project!;
  415. const searchScope = {
  416. scopes: [{ ...project, scope: "project" as const }],
  417. unavailableSources: [{ sourceServerId: "source-b", reason: "disconnected" }],
  418. };
  419. ports.app.sessions.listSessions = async () => ({ sessions: [], searchScope });
  420. ports.app.projects.listProjects = async () => ({ projects: [], searchScope });
  421. await expect(control.listSessions({ ...ctx, discoveryScopes }, {})).resolves.toEqual({
  422. sessions: [],
  423. searchScope,
  424. });
  425. await expect(control.listProjects({ ...ctx, discoveryScopes }, {})).resolves.toEqual({
  426. projects: [],
  427. searchScope,
  428. });
  429. const unavailableOnly = {
  430. scopes: [],
  431. unavailableSources: [{ sourceServerId: "source-a", reason: "disconnected" }],
  432. };
  433. ports.app.sessions.listSessions = async () => ({ sessions: [], searchScope: unavailableOnly });
  434. await expect(control.listSessions({ ...ctx, discoveryScopes }, {})).resolves.toEqual({
  435. sessions: [],
  436. searchScope: unavailableOnly,
  437. });
  438. });
  439. it.each(["host-widening", "wrong-source", "wrong-project"])(
  440. "rejects %s in list searchScope even when no rows are returned",
  441. async (kind) => {
  442. const { control, ctx, ports } = appFixture();
  443. const project = ctx.rootSession.project!;
  444. const allowed: AppScope = { ...project, scope: "project" };
  445. const scopes: AppScope[] =
  446. kind === "host-widening"
  447. ? [{ kind: "app", scope: "host", sourceServerId: "source-a" }]
  448. : [
  449. {
  450. ...allowed,
  451. ...(kind === "wrong-source"
  452. ? { sourceServerId: "source-b" }
  453. : kind === "wrong-project"
  454. ? { projectId: "private" }
  455. : {}),
  456. },
  457. ];
  458. const searchScope = {
  459. scopes,
  460. unavailableSources: [],
  461. };
  462. ports.app.sessions.listSessions = async () => ({ sessions: [], searchScope });
  463. ports.app.projects.listProjects = async () => ({ projects: [], searchScope });
  464. const discovery = { ...ctx, discoveryScopes: [allowed] };
  465. await expect(control.listSessions(discovery, {})).rejects.toMatchObject({
  466. code: "invalid_output",
  467. });
  468. await expect(control.listProjects(discovery, {})).rejects.toMatchObject({
  469. code: "invalid_output",
  470. });
  471. },
  472. );
  473. it("reports unavailable legacy sources without granting discovery or accepting their rows", async () => {
  474. const { control, ctx, ports } = appFixture();
  475. const discovery = { ...ctx, discoveryScopes: [] };
  476. const searchScope = {
  477. scopes: [],
  478. unavailableSources: [
  479. { sourceServerId: "legacy-source", reason: "project identity unavailable" },
  480. ],
  481. };
  482. ports.app.sessions.listSessions = async () => ({ sessions: [], searchScope });
  483. ports.app.projects.listProjects = async () => ({ projects: [], searchScope });
  484. await expect(control.listSessions(discovery, {})).resolves.toEqual({
  485. sessions: [],
  486. searchScope,
  487. });
  488. await expect(control.listProjects(discovery, {})).resolves.toEqual({
  489. projects: [],
  490. searchScope,
  491. });
  492. expect(ports.calls).toEqual([]);
  493. const project = { kind: "app" as const, projectId: "private", sourceServerId: "legacy-source" };
  494. const session = { ...appTarget, sourceServerId: "legacy-source", project };
  495. ports.app.sessions.listSessions = async () => ({
  496. sessions: [{ session, title: "private", status: "idle", availableActions: [] }],
  497. searchScope,
  498. });
  499. ports.app.projects.listProjects = async () => ({
  500. projects: [{ project, title: "private" }],
  501. searchScope,
  502. });
  503. await expect(control.listSessions(discovery, {})).rejects.toMatchObject({
  504. code: "invalid_output",
  505. });
  506. await expect(control.listProjects(discovery, {})).rejects.toMatchObject({
  507. code: "invalid_output",
  508. });
  509. await expect(control.listSessions(discovery, { project })).rejects.toMatchObject({
  510. code: "forbidden",
  511. });
  512. await expect(
  513. control.readSession(discovery, { session, view: "messages" }),
  514. ).rejects.toMatchObject({ code: "forbidden" });
  515. await expect(
  516. control.sendToSession(discovery, { session, prompt: "go", requestId: "legacy-denied" }),
  517. ).rejects.toMatchObject({ code: "forbidden" });
  518. });
  519. it("validates searchScope against an explicit project filter and against the granted sources", async () => {
  520. const { control, ctx, ports } = appFixture();
  521. const discoveryScopes: AppScope[] = [
  522. { kind: "app", scope: "host", sourceServerId: "source-a" },
  523. { kind: "app", scope: "host", sourceServerId: "source-b" },
  524. ];
  525. const discovery = { ...ctx, discoveryScopes };
  526. ports.app.sessions.listSessions = async () => ({
  527. sessions: [],
  528. searchScope: { scopes: discoveryScopes, unavailableSources: [] },
  529. });
  530. // host 过滤器已删除(规格 0.14),发现范围恒为全部授权来源;回执仍不得声明超出授权的范围。
  531. ports.app.projects.listProjects = async () => ({
  532. projects: [],
  533. searchScope: {
  534. scopes: [...discoveryScopes, { kind: "app", scope: "host", sourceServerId: "source-c" }],
  535. unavailableSources: [],
  536. },
  537. });
  538. await expect(
  539. control.listSessions(discovery, { project: ctx.rootSession.project }),
  540. ).rejects.toMatchObject({ code: "invalid_output" });
  541. await expect(control.listProjects(discovery, {})).rejects.toMatchObject({
  542. code: "invalid_output",
  543. });
  544. });
  545. it("rejects rows that are authorized but absent from the reported successful search", async () => {
  546. const { control, ctx, ports } = appFixture();
  547. const discovery = {
  548. ...ctx,
  549. discoveryScopes: [{ kind: "app", scope: "host", sourceServerId: "source-a" }] as AppScope[],
  550. };
  551. const project = ctx.rootSession.project!;
  552. const searchScope = {
  553. scopes: [],
  554. unavailableSources: [{ sourceServerId: "source-a", reason: "disconnected" }],
  555. };
  556. ports.app.sessions.listSessions = async () => ({
  557. sessions: [
  558. { session: { ...appTarget, project }, title: "late", status: "idle", availableActions: [] },
  559. ],
  560. searchScope,
  561. });
  562. ports.app.projects.listProjects = async () => ({
  563. projects: [{ project, title: "late" }],
  564. searchScope,
  565. });
  566. await expect(control.listSessions(discovery, {})).rejects.toMatchObject({
  567. code: "invalid_output",
  568. });
  569. await expect(control.listProjects(discovery, {})).rejects.toMatchObject({
  570. code: "invalid_output",
  571. });
  572. });
  573. it("read, archive and pin do not navigate, stop or send", async () => {
  574. const { control, ctx, ports } = appFixture();
  575. await control.readSession(ctx, { session: appTarget, view: "messages" });
  576. await control.setSessionArchived(ctx, {
  577. session: appTarget,
  578. archived: true,
  579. requestId: "archive",
  580. });
  581. await control.setSessionPinned(ctx, { session: appTarget, pinned: true, requestId: "pin" });
  582. expect(ports.calls.map((call) => call.method)).toEqual([
  583. "authorize",
  584. "readSession",
  585. "authorize",
  586. "setSessionArchived",
  587. "authorize",
  588. "setSessionPinned",
  589. ]);
  590. });
  591. it("uses target project configuration and retains creation versus first-input outcomes", async () => {
  592. const { control, ctx, ports } = appFixture();
  593. const project = { kind: "app" as const, projectId: "project-1", sourceServerId: "source-a" };
  594. await control.createSession(ctx, {
  595. project,
  596. prompt: "go",
  597. requestId: "create",
  598. model: "model-choice",
  599. });
  600. expect(ports.calls.at(-1)?.input).toEqual({
  601. project,
  602. prompt: "go",
  603. requestId: "create",
  604. model: "model-choice",
  605. });
  606. expect(ports.calls.map((call) => call.method)).toEqual(["authorize", "createSession"]);
  607. });
  608. it("uses trusted UI target and reports missing navigation without affecting reads", async () => {
  609. const { control, ctx, ports } = appFixture();
  610. await control.openSession({ ...ctx, uiTarget: "window-1" }, { session: appTarget });
  611. expect(ports.calls.at(-1)?.input).toMatchObject({ uiTarget: "window-1" });
  612. const noUi = createAppSessionControl({ ...ports.app, navigation: undefined });
  613. await expect(noUi.openSession(ctx, { session: appTarget })).resolves.toEqual({
  614. status: "unavailable",
  615. reason: "navigation_unavailable",
  616. });
  617. await expect(
  618. noUi.readSession(ctx, { session: appTarget, view: "summary" }),
  619. ).resolves.toMatchObject({ view: "summary" });
  620. });
  621. it("lists only authorized project grants and rejects source leakage", async () => {
  622. const { control, ctx, ports } = appFixture();
  623. await control.listProjects(ctx, {});
  624. expect(ports.calls.map((call) => call.method)).toEqual(["authorize", "listProjects"]);
  625. ports.app.projects.listProjects = async () => ({
  626. projects: [
  627. {
  628. project: { kind: "app", projectId: "project-1", sourceServerId: "source-b" },
  629. title: "private",
  630. },
  631. ],
  632. searchScope: { scopes: [ctx.allowedScopes[0]!], unavailableSources: [] },
  633. });
  634. await expect(control.listProjects(ctx, {})).rejects.toMatchObject({ code: "invalid_output" });
  635. });
  636. it("does not enter an owner after cancellation during access", async () => {
  637. const { control, ctx, ports } = appFixture();
  638. const controller = new AbortController();
  639. ports.app.access.authorize = async (_ctx, request) => {
  640. controller.abort();
  641. return { scope: request.scope, fence: "epoch" };
  642. };
  643. await expect(
  644. control.sendToSession(
  645. { ...ctx, signal: controller.signal },
  646. { session: appTarget, prompt: "go", requestId: "r" },
  647. ),
  648. ).rejects.toMatchObject({ code: "cancelled" });
  649. expect(ports.calls).toEqual([]);
  650. });
  651. });