@allbluecn/collab-server 0.0.0-stage → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +126 -2
  3. package/package.json +64 -3
  4. package/src/__tests__/clients.test.ts +93 -0
  5. package/src/__tests__/embed.test.ts +227 -0
  6. package/src/__tests__/env-setup.ts +33 -0
  7. package/src/__tests__/exporters-bug.test.ts +552 -0
  8. package/src/__tests__/exporters-case.test.ts +356 -0
  9. package/src/__tests__/exporters-design.test.ts +356 -0
  10. package/src/__tests__/exporters-knowledge.test.ts +366 -0
  11. package/src/__tests__/exporters-stats.test.ts +105 -0
  12. package/src/__tests__/exporters-story.test.ts +519 -0
  13. package/src/__tests__/internal-apply-channel.test.ts +233 -0
  14. package/src/__tests__/internal-apply-race.test.ts +165 -0
  15. package/src/__tests__/internal-apply.test.ts +418 -0
  16. package/src/__tests__/multiplex.test.ts +166 -0
  17. package/src/__tests__/persistence-retry.test.ts +262 -0
  18. package/src/__tests__/persistence.test.ts +302 -0
  19. package/src/__tests__/server.test.ts +145 -0
  20. package/src/__tests__/share-room-limit.test.ts +183 -0
  21. package/src/__tests__/shutdown.test.ts +130 -0
  22. package/src/__tests__/test-utils.ts +176 -0
  23. package/src/auth.ts +84 -0
  24. package/src/clients.ts +133 -0
  25. package/src/embed.ts +156 -0
  26. package/src/exporters/bug.ts +454 -0
  27. package/src/exporters/case.ts +317 -0
  28. package/src/exporters/design.ts +268 -0
  29. package/src/exporters/entity-shared.ts +75 -0
  30. package/src/exporters/knowledge.ts +259 -0
  31. package/src/exporters/story.ts +483 -0
  32. package/src/exporters.ts +173 -0
  33. package/src/index.ts +354 -0
  34. package/src/internal-apply-limit.ts +99 -0
  35. package/src/internal-apply.ts +888 -0
  36. package/src/metrics.ts +82 -0
  37. package/src/persistence.ts +409 -0
  38. package/src/rooms.ts +32 -0
  39. package/src/share-room-limit.ts +73 -0
@@ -0,0 +1,552 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+
10
+ // Bug 回写导出器 + /internal/apply entity-bug 集成测试(Yjs 多人协作 §5.2 回写
11
+ // / §5.3 写入路由 / §10.2 持久来源,任务 22;真实 WS + 真实共享开发库,
12
+ // test-exp- 前缀精确清理——结构对齐 exporters-story 先例):
13
+ //
14
+ // 1. 协同落库后 Bug 各列与 Y 状态一致:description({html,markdown} JSON 串,
15
+ // 空产物 → null)+ 6 字段(含 BugLabel diff 同步)+ reproduceSteps.steps
16
+ // (order 按索引+1 归一、expectedResult/actualResult 保留)
17
+ // 2. 活动:BugActivity.actorType="collab"(schema 已有字段)+ 归属作者
18
+ // 3. 锚点 M②:CollabDocument.updatedAt ≥ bug.updatedAt
19
+ // 4. /internal/apply entity:bug:在线 → content replace + fields merge + steps
20
+ // replace 进 Y;离线 → collab 直落业务列 + 快照行不触碰
21
+ // 5. 幽灵 room 拒绝
22
+
23
+ import { afterEach, beforeEach, describe, expect, test } from "vitest";
24
+ import * as Y from "yjs";
25
+ import { HocuspocusProvider } from "@hocuspocus/provider";
26
+ import { buildRoomName } from "@allbluecn/collab-core/rooms";
27
+ import {
28
+ INTERNAL_DOMAIN_APPLY,
29
+ INTERNAL_SIGNATURE_HEADER,
30
+ signInternalRequest,
31
+ } from "@allbluecn/collab-core/internal";
32
+ import { seedYDocFromHtml } from "@allbluecn/collab-core/tiptap-export";
33
+ import { applyStepsToDoc } from "@allbluecn/collab-core/steps";
34
+ import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
35
+ import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
36
+ import { prisma } from "@allbluecn/database";
37
+ import {
38
+ TEST_SECRET,
39
+ connectProvider,
40
+ issueTicket,
41
+ sleep,
42
+ startCollabServer,
43
+ waitUntil,
44
+ type ProviderSession,
45
+ type StartedServer,
46
+ } from "./test-utils";
47
+ import { ensureServerDom, registerKnowledgeCollab } from "../exporters/knowledge";
48
+ import { registerBugCollab } from "../exporters/bug";
49
+ import { resetExporters, resetRoomGuards } from "../exporters";
50
+
51
+ /** 测试资源前缀(bugId / userId / projectId / labelId 共用) */
52
+ const PREFIX = "test-exp-";
53
+ const ROOM_LIKE = `entity:bug:${PREFIX}`;
54
+
55
+ interface TestBug {
56
+ actorId: string;
57
+ otherUserId: string;
58
+ projectId: string;
59
+ bugId: string;
60
+ labelIds: string[];
61
+ room: string;
62
+ }
63
+
64
+ function rand(): string {
65
+ return Math.random().toString(36).slice(2, 10);
66
+ }
67
+
68
+ /** 建 BUG 测试行:双 User → Project → Bug(带描述与复现步骤)→ 2 Label 挂 [0] */
69
+ async function createBugFixture(): Promise<TestBug> {
70
+ const suffix = rand();
71
+ const actorId = `${PREFIX}user-${suffix}`;
72
+ const otherUserId = `${PREFIX}user-${suffix}-b`;
73
+ const projectId = `${PREFIX}proj-${suffix}`;
74
+ const bugId = `${PREFIX}bug-${suffix}`;
75
+ for (const [id, email] of [
76
+ [actorId, `${suffix}@collab-bug.test`],
77
+ [otherUserId, `${suffix}-b@collab-bug.test`],
78
+ ] as const) {
79
+ await prisma.user.create({
80
+ data: { id, email, username: `collab-bug-${id.slice(PREFIX.length)}`, password: "test-only" },
81
+ });
82
+ }
83
+ await prisma.project.create({
84
+ data: { id: projectId, name: "Bug 协同回写测试项目", ownerId: actorId },
85
+ });
86
+ await prisma.bug.create({
87
+ data: {
88
+ id: bugId,
89
+ sequenceId: 1,
90
+ identifier: `BUG-${suffix}`,
91
+ projectId,
92
+ title: "旧标题",
93
+ description: JSON.stringify({ html: "<p>旧描述</p>", markdown: "旧描述" }),
94
+ reproduceSteps: {
95
+ steps: [
96
+ { order: 1, action: "旧步骤一", expected: "旧预期一" },
97
+ { order: 2, action: "旧步骤二" },
98
+ ],
99
+ expectedResult: "整体预期(保留)",
100
+ actualResult: "整体实际(保留)",
101
+ },
102
+ createdById: actorId,
103
+ },
104
+ });
105
+ const labelIds: string[] = [];
106
+ for (let i = 0; i < 2; i++) {
107
+ const labelId = `${PREFIX}label-${suffix}-${i}`;
108
+ await prisma.label.create({
109
+ data: { id: labelId, name: `Bug 协同标签-${suffix}-${i}`, createdById: actorId },
110
+ });
111
+ labelIds.push(labelId);
112
+ }
113
+ await prisma.bugLabel.create({ data: { bugId, labelId: labelIds[0]! } });
114
+ const room = buildRoomName({ kind: "entity-bug", bugId });
115
+ return { actorId, otherUserId, projectId, bugId, labelIds, room };
116
+ }
117
+
118
+ async function cleanOwnRows(): Promise<void> {
119
+ await prisma.collabUpdate.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
120
+ await prisma.collabClient.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
121
+ await prisma.collabDocument.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
122
+ await prisma.bugActivity.deleteMany({ where: { bugId: { startsWith: PREFIX } } });
123
+ await prisma.bugLabel.deleteMany({ where: { bugId: { startsWith: PREFIX } } });
124
+ await prisma.bug.deleteMany({ where: { id: { startsWith: PREFIX } } });
125
+ await prisma.label.deleteMany({ where: { id: { startsWith: PREFIX } } });
126
+ await prisma.project.deleteMany({ where: { id: { startsWith: PREFIX } } });
127
+ await prisma.user.deleteMany({ where: { id: { startsWith: PREFIX } } });
128
+ const residue =
129
+ (await prisma.collabDocument.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
130
+ (await prisma.bug.count({ where: { id: { startsWith: PREFIX } } })) +
131
+ (await prisma.user.count({ where: { id: { startsWith: PREFIX } } }));
132
+ expect(residue).toBe(0);
133
+ }
134
+
135
+ /** 与种子化同一扩展组合把 HTML 变成 Y update */
136
+ function htmlToUpdates(html: string): Uint8Array {
137
+ const yDoc = seedYDocFromHtml(html, [
138
+ ...createKnowledgeExtensions(),
139
+ ...createKnowledgeDocAdditions(),
140
+ ]);
141
+ return Y.encodeStateAsUpdate(yDoc);
142
+ }
143
+
144
+ function htmlToState(html: string): Uint8Array<ArrayBuffer> {
145
+ return new Uint8Array(htmlToUpdates(html));
146
+ }
147
+
148
+ async function postApply(ctx: StartedServer, payload: Record<string, unknown>): Promise<Response> {
149
+ const signed = signInternalRequest({
150
+ secret: TEST_SECRET,
151
+ domain: INTERNAL_DOMAIN_APPLY,
152
+ payload,
153
+ });
154
+ return fetch(`http://127.0.0.1:${ctx.port}/internal/apply`, {
155
+ method: "POST",
156
+ headers: {
157
+ "content-type": "application/json",
158
+ [INTERNAL_SIGNATURE_HEADER]: signed.headers[INTERNAL_SIGNATURE_HEADER]!,
159
+ },
160
+ body: signed.body,
161
+ });
162
+ }
163
+
164
+ async function pollDb(check: () => Promise<boolean>, label: string, timeoutMs = 20000): Promise<void> {
165
+ const deadline = Date.now() + timeoutMs;
166
+ while (!(await check())) {
167
+ if (Date.now() > deadline) throw new Error(`pollDb 超时(${label})`);
168
+ await sleep(50);
169
+ }
170
+ }
171
+
172
+ describe("bug exporter + /internal/apply entity-bug(真实 WS + 真实库)", () => {
173
+ let ctx: StartedServer;
174
+ let session: ProviderSession | null = null;
175
+
176
+ beforeEach(async () => {
177
+ await ensureServerDom();
178
+ registerKnowledgeCollab();
179
+ registerBugCollab();
180
+ ctx = await startCollabServer({ persistence: {}, debounceMs: 300 });
181
+ });
182
+
183
+ afterEach(async () => {
184
+ session?.destroy();
185
+ session = null;
186
+ await ctx?.stop();
187
+ resetExporters();
188
+ resetRoomGuards();
189
+ await cleanOwnRows();
190
+ });
191
+
192
+ test("场景 1:协同落库后 Bug 各列与 Y 状态一致(description 双轨 + 6 字段 + 标签 diff + steps 归一)", async () => {
193
+ const fx = await createBugFixture();
194
+ await prisma.collabDocument.create({
195
+ data: { roomName: fx.room, state: htmlToState("<p>旧描述</p>") },
196
+ });
197
+
198
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
199
+ const doc = session.provider.document as Y.Doc;
200
+ Y.applyUpdate(doc, htmlToUpdates("<p>协同新描述</p>"));
201
+ doc.transact(() => {
202
+ const fields = doc.getMap("fields");
203
+ fields.set("title", "协同新标题");
204
+ fields.set("state", "in_progress");
205
+ fields.set("severity", "high");
206
+ fields.set("assigneeId", fx.otherUserId);
207
+ fields.set("labelIds", [fx.labelIds[1]]);
208
+ fields.set("env", "staging");
209
+ });
210
+ // steps:删旧步骤二 + 改步骤一动作 + 尾部新增(Y 侧无 order)
211
+ doc.transact(() => {
212
+ applyStepsToDoc(doc, [
213
+ { action: "新步骤一", expected: "新预期一" },
214
+ { action: "新步骤二", expected: "新预期二" },
215
+ { action: "新步骤三" },
216
+ ]);
217
+ });
218
+
219
+ await pollDb(async () => {
220
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
221
+ return row?.title === "协同新标题" && row?.state === "in_progress";
222
+ }, "字段落库");
223
+
224
+ const row = await prisma.bug.findUnique({
225
+ where: { id: fx.bugId },
226
+ include: { labels: true },
227
+ });
228
+ expect(row!.title).toBe("协同新标题");
229
+ expect(row!.state).toBe("in_progress");
230
+ expect(row!.severity).toBe("high");
231
+ expect(row!.assigneeId).toBe(fx.otherUserId);
232
+ expect(row!.env).toBe("staging");
233
+ expect(row!.labels.map((l) => l.labelId)).toEqual([fx.labelIds[1]]);
234
+ const desc = JSON.parse(row!.description!) as { html: string; markdown: string };
235
+ expect(desc.html).toContain("协同新描述");
236
+ expect(desc.markdown).toContain("协同新描述");
237
+ // steps:order 按索引+1 归一;expectedResult/actualResult 从业务列保留
238
+ const steps = row!.reproduceSteps as {
239
+ steps: Array<{ order: number; action: string; expected?: string }>;
240
+ expectedResult?: string;
241
+ actualResult?: string;
242
+ };
243
+ expect(steps.steps).toEqual([
244
+ { order: 1, action: "新步骤一", expected: "新预期一" },
245
+ { order: 2, action: "新步骤二", expected: "新预期二" },
246
+ { order: 3, action: "新步骤三" },
247
+ ]);
248
+ expect(steps.expectedResult).toBe("整体预期(保留)");
249
+ expect(steps.actualResult).toBe("整体实际(保留)");
250
+ });
251
+
252
+ test("场景 2:活动 actorType=collab + 归属作者;CollabDocument.updatedAt ≥ bug.updatedAt(锚点 M②)", async () => {
253
+ const fx = await createBugFixture();
254
+ await prisma.collabDocument.create({
255
+ data: { roomName: fx.room, state: htmlToState("<p>起点</p>") },
256
+ });
257
+
258
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
259
+ const doc = session.provider.document as Y.Doc;
260
+ Y.applyUpdate(doc, htmlToUpdates("<p>归属作者的活动</p>"));
261
+ doc.getMap("fields").set("severity", "critical");
262
+
263
+ await pollDb(async () => {
264
+ const rows = await prisma.bugActivity.findMany({
265
+ where: { bugId: fx.bugId, action: "collab_update" },
266
+ });
267
+ return rows.length > 0;
268
+ }, "协同活动落库");
269
+
270
+ const activities = await prisma.bugActivity.findMany({
271
+ where: { bugId: fx.bugId, action: "collab_update" },
272
+ });
273
+ expect(activities).toHaveLength(1);
274
+ const activity = activities[0]!;
275
+ // BugActivity 独有 actorType 字段:协同活动直接用 "collab" 值
276
+ expect(activity.actorType).toBe("collab");
277
+ expect(activity.userId).toBe(fx.actorId);
278
+ const meta = activity.metadata as { source?: string; changedFields?: string[] };
279
+ expect(meta.source).toBe("collab");
280
+ expect(meta.changedFields).toContain("description");
281
+ expect(meta.changedFields).toContain("severity");
282
+
283
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
284
+ const snap = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
285
+ expect(row!.updatedAt.getTime()).toBeLessThanOrEqual(snap!.updatedAt.getTime());
286
+ });
287
+
288
+ test("场景 3:/internal/apply entity-bug 在线 → content replace + fields merge + steps replace 进 Y", async () => {
289
+ const fx = await createBugFixture();
290
+ await prisma.collabDocument.create({
291
+ data: { roomName: fx.room, state: htmlToState("<p>初始</p>") },
292
+ });
293
+
294
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
295
+ const res = await postApply(ctx, {
296
+ roomName: fx.room,
297
+ docId: fx.bugId,
298
+ actor: fx.actorId,
299
+ patch: {
300
+ content: { html: "<p>外部权威描述</p>" },
301
+ fields: { state: "fixed" },
302
+ steps: [{ action: "旁路步骤一", expected: "旁路预期" }],
303
+ },
304
+ });
305
+ expect(res.status).toBe(202);
306
+ // 同 exporters-case:容忍在线判定握手窗口的离线误判(db + reapplied 补偿)终态
307
+ const appliedBody = (await res.json()) as { applied: string; reapplied?: string };
308
+ if (appliedBody.applied === "db") {
309
+ expect(appliedBody.reapplied).toBe("ydoc");
310
+ } else {
311
+ expect(appliedBody.applied).toBe("ydoc");
312
+ }
313
+
314
+ const doc = session.provider.document as Y.Doc;
315
+ await waitUntil(() => doc.getMap("fields").get("state") === "fixed", "fields 未广播");
316
+ await waitUntil(() => {
317
+ const json = JSON.stringify(doc.getXmlFragment("default").toJSON());
318
+ return json.includes("外部权威描述") && !json.includes("初始");
319
+ }, "description 未广播");
320
+ await waitUntil(
321
+ () => {
322
+ const arr = doc.getArray("steps");
323
+ return arr.length === 1 && (arr.get(0) as Y.Map<unknown>).get("action") === "旁路步骤一";
324
+ },
325
+ "steps 未广播",
326
+ );
327
+
328
+ // 落库走 onStoreDocument 统一链路
329
+ await pollDb(async () => {
330
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
331
+ return row?.state === "fixed";
332
+ }, "字段经 exporter 落库");
333
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
334
+ const steps = row!.reproduceSteps as { steps: Array<{ order: number; action: string }> };
335
+ expect(steps.steps).toEqual([{ order: 1, action: "旁路步骤一", expected: "旁路预期" }]);
336
+ });
337
+
338
+ test("场景 4:/internal/apply entity-bug 离线 → collab 直落业务列 + 快照行不触碰(重种子化判定成立)", async () => {
339
+ const fx = await createBugFixture();
340
+ const oldState = htmlToState("<p>旧描述</p>");
341
+ await prisma.collabDocument.create({ data: { roomName: fx.room, state: oldState } });
342
+ const snapBefore = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
343
+
344
+ const res = await postApply(ctx, {
345
+ roomName: fx.room,
346
+ docId: fx.bugId,
347
+ actor: fx.actorId,
348
+ patch: {
349
+ fields: { title: "旁路新标题", state: "closed" },
350
+ steps: [{ action: "旁路唯一步骤" }],
351
+ },
352
+ });
353
+ expect(res.status).toBe(202);
354
+ expect(await res.json()).toMatchObject({ applied: "db" });
355
+
356
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
357
+ expect(row!.title).toBe("旁路新标题");
358
+ expect(row!.state).toBe("closed");
359
+ const steps = row!.reproduceSteps as {
360
+ steps: Array<{ order: number; action: string; expectedResult?: string }>;
361
+ expectedResult?: string;
362
+ };
363
+ expect(steps.steps).toEqual([{ order: 1, action: "旁路唯一步骤" }]);
364
+ // expectedResult/actualResult 保留(旁路 steps patch 只拥有 steps 列表)
365
+ expect(steps.expectedResult).toBe("整体预期(保留)");
366
+
367
+ const activity = await prisma.bugActivity.findFirst({
368
+ where: { bugId: fx.bugId, action: "collab_update" },
369
+ });
370
+ expect(activity?.userId).toBe(fx.actorId);
371
+ expect(activity?.actorType).toBe("collab");
372
+
373
+ const snapAfter = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
374
+ expect(Buffer.from(snapAfter!.state).equals(Buffer.from(oldState))).toBe(true);
375
+ expect(snapAfter!.updatedAt).toEqual(snapBefore!.updatedAt);
376
+ expect(row!.updatedAt.getTime()).toBeGreaterThan(snapAfter!.updatedAt.getTime());
377
+ });
378
+
379
+ test("场景 6(任务 23):机器 actor 在线 apply(真 WS)→ Y 广播 + 落库活动 actorType=sdk 保留(userId=null)", async () => {
380
+ const fx = await createBugFixture();
381
+ await prisma.collabDocument.create({
382
+ data: { roomName: fx.room, state: htmlToState("<p>起点</p>") },
383
+ });
384
+
385
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
386
+ // SDK 上报重开语义:机器身份 actor(sdk:<source>)经 /internal/apply 进 Y
387
+ const res = await postApply(ctx, {
388
+ roomName: fx.room,
389
+ docId: fx.bugId,
390
+ actor: "sdk:bug-report",
391
+ patch: { fields: { state: "open" } },
392
+ });
393
+ expect(res.status).toBe(202);
394
+ // 同 exporters-case:容忍在线判定握手窗口的离线误判(db + reapplied 补偿)终态
395
+ const appliedBody = (await res.json()) as { applied: string; reapplied?: string };
396
+ if (appliedBody.applied === "db") {
397
+ expect(appliedBody.reapplied).toBe("ydoc");
398
+ } else {
399
+ expect(appliedBody.applied).toBe("ydoc");
400
+ }
401
+
402
+ // Y 广播可达在线协同端
403
+ const doc = session.provider.document as Y.Doc;
404
+ await waitUntil(() => doc.getMap("fields").get("state") === "open", "state 未广播");
405
+
406
+ // 落库走 onStoreDocument 统一链路,活动 actorType=sdk 保留(非 collab)
407
+ await pollDb(async () => {
408
+ const rows = await prisma.bugActivity.findMany({
409
+ where: { bugId: fx.bugId, action: "collab_update" },
410
+ });
411
+ return rows.length > 0;
412
+ }, "机器写入活动落库");
413
+ const activity = await prisma.bugActivity.findFirst({
414
+ where: { bugId: fx.bugId, action: "collab_update" },
415
+ });
416
+ expect(activity).not.toBeNull();
417
+ expect(activity!.actorType).toBe("sdk");
418
+ expect(activity!.userId).toBeNull();
419
+ const meta = activity!.metadata as { source?: string };
420
+ expect(meta.source).toBe("sdk");
421
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
422
+ expect(row!.state).toBe("open");
423
+ });
424
+
425
+ test("场景 6b(followup):reopened_by_sdk 语义 hint——live 入队随落库成行且压制通用机器行", async () => {
426
+ const fx = await createBugFixture();
427
+ await prisma.collabDocument.create({
428
+ data: { roomName: fx.room, state: new Uint8Array(Y.encodeStateAsUpdate(new Y.Doc())) },
429
+ });
430
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
431
+
432
+ const res = await postApply(ctx, {
433
+ roomName: fx.room,
434
+ docId: fx.bugId,
435
+ actor: "sdk:bug-report",
436
+ patch: { fields: { state: "open" } },
437
+ activity: { action: "reopened_by_sdk", field: "state", oldValue: "fixed", newValue: "open" },
438
+ });
439
+ expect(res.status).toBe(202);
440
+
441
+ const doc = session.provider.document as Y.Doc;
442
+ await waitUntil(() => doc.getMap("fields").get("state") === "open", "state 未广播");
443
+
444
+ // 落库后:语义行(reopened_by_sdk)存在、通用机器行(collab_update×sdk)被压制
445
+ await pollDb(async () => {
446
+ const semantic = await prisma.bugActivity.findFirst({
447
+ where: { bugId: fx.bugId, action: "reopened_by_sdk" },
448
+ });
449
+ return semantic != null;
450
+ }, "语义活动行落库");
451
+ const semantic = await prisma.bugActivity.findFirst({
452
+ where: { bugId: fx.bugId, action: "reopened_by_sdk" },
453
+ });
454
+ expect(semantic!.actorType).toBe("sdk");
455
+ expect(semantic!.userId).toBeNull();
456
+ const meta = semantic!.metadata as { oldValue?: string; newValue?: string; field?: string };
457
+ expect(meta.oldValue).toBe("fixed");
458
+ expect(meta.newValue).toBe("open");
459
+ expect(meta.field).toBe("state");
460
+ const genericSdk = await prisma.bugActivity.findFirst({
461
+ where: { bugId: fx.bugId, action: "collab_update", actorType: "sdk" },
462
+ });
463
+ expect(genericSdk).toBeNull();
464
+ });
465
+
466
+ test("场景 6c(followup):reopened_by_sdk 语义 hint——离线直落随活动行携带", async () => {
467
+ const fx = await createBugFixture();
468
+ await prisma.collabDocument.create({
469
+ data: { roomName: fx.room, state: new Uint8Array(Y.encodeStateAsUpdate(new Y.Doc())) },
470
+ });
471
+ // fixture 默认 state=open——先置 closed 才有 state diff(无 diff 即止语义)
472
+ await prisma.bug.update({ where: { id: fx.bugId }, data: { state: "closed" } });
473
+ const res = await postApply(ctx, {
474
+ roomName: fx.room,
475
+ docId: fx.bugId,
476
+ actor: "sdk:bug-report",
477
+ patch: { fields: { state: "open" } },
478
+ activity: { action: "reopened_by_sdk", field: "state", oldValue: "closed", newValue: "open" },
479
+ });
480
+ expect(res.status).toBe(202);
481
+
482
+ await pollDb(async () => {
483
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
484
+ const semantic = await prisma.bugActivity.findFirst({
485
+ where: { bugId: fx.bugId, action: "reopened_by_sdk" },
486
+ });
487
+ return row?.state === "open" && semantic != null;
488
+ }, "离线直落 + 语义活动行");
489
+ const semantic = await prisma.bugActivity.findFirst({
490
+ where: { bugId: fx.bugId, action: "reopened_by_sdk" },
491
+ });
492
+ expect(semantic!.actorType).toBe("sdk");
493
+ const meta = semantic!.metadata as { oldValue?: string; newValue?: string };
494
+ expect(meta.oldValue).toBe("closed");
495
+ expect(meta.newValue).toBe("open");
496
+ });
497
+
498
+ test("场景 7(任务 23):agent actor 离线直落 → 活动 actorType=agent + agentName 保留", async () => {
499
+ const fx = await createBugFixture();
500
+ await prisma.collabDocument.create({
501
+ data: { roomName: fx.room, state: htmlToState("<p>起点</p>") },
502
+ });
503
+
504
+ // room 无连接(离线)→ collab 直落业务列;机器身份原样落活动
505
+ const res = await postApply(ctx, {
506
+ roomName: fx.room,
507
+ docId: fx.bugId,
508
+ actor: "agent:opencode",
509
+ patch: { fields: { state: "fixed" } },
510
+ });
511
+ expect(res.status).toBe(202);
512
+ expect(await res.json()).toMatchObject({ applied: "db" });
513
+
514
+ const row = await prisma.bug.findUnique({ where: { id: fx.bugId } });
515
+ expect(row!.state).toBe("fixed");
516
+ const activity = await prisma.bugActivity.findFirst({
517
+ where: { bugId: fx.bugId, action: "collab_update" },
518
+ });
519
+ expect(activity).not.toBeNull();
520
+ expect(activity!.actorType).toBe("agent");
521
+ expect(activity!.agentName).toBe("opencode");
522
+ expect(activity!.userId).toBeNull();
523
+ });
524
+
525
+ test("场景 5:幽灵 room——bug 不存在拒绝装载;已删实体离线 apply 409 且零写入", async () => {
526
+ const ghostRoom = buildRoomName({ kind: "entity-bug", bugId: `${PREFIX}ghost-${rand()}` });
527
+ let rejected = false;
528
+ const ghostProvider = new HocuspocusProvider({
529
+ url: ctx.url,
530
+ name: ghostRoom,
531
+ token: issueTicket(ghostRoom, { sub: `${PREFIX}user-ghost` }),
532
+ });
533
+ ghostProvider.on("authenticationFailed", () => {
534
+ rejected = true;
535
+ });
536
+ await pollDb(() => Promise.resolve(rejected), "幽灵 bug room 被拒绝装载");
537
+ expect(ctx.server.hocuspocus.documents.has(ghostRoom)).toBe(false);
538
+ ghostProvider.destroy();
539
+
540
+ const fx = await createBugFixture();
541
+ await prisma.bug.delete({ where: { id: fx.bugId } });
542
+ const res = await postApply(ctx, {
543
+ roomName: fx.room,
544
+ docId: fx.bugId,
545
+ actor: fx.actorId,
546
+ patch: { fields: { state: "fixed" } },
547
+ });
548
+ expect(res.status).toBe(409);
549
+ const restored = await prisma.bug.findUnique({ where: { id: fx.bugId } });
550
+ expect(restored).toBeNull();
551
+ });
552
+ });