| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691 |
- import { TestBed } from '@angular/core/testing';
- import { ChatSessionService } from './chat-session.service';
- import { FmodeApi } from './api/fmode-api';
- import { SessionService } from './session.service';
- import { legacySessionId } from './chat-session';
- /**
- * ChatSessionService —— 会话目录的唯一 owner。
- *
- * 覆盖:新建 / 归档 / 重命名 / 移除黑名单 / 云端单向同步 / 持久化。
- * 这些是「多会话」的数据底座,错一个字段用户就会看到串号的对话名。
- */
- /**
- * 以「带 FmodeApi 桩」的方式构造服务实例。
- *
- * 文件级声明:多个 describe 都要用它构造独立实例,
- * 每次重建都拿到干净的 signal 状态(`resetTestingModule`)。
- */
- function withApiStub(api: Record<string, unknown>): ChatSessionService {
- TestBed.resetTestingModule();
- TestBed.configureTestingModule({
- providers: [
- ChatSessionService,
- { provide: SessionService, useValue: { me: () => ({ id: 'u1' }) } },
- { provide: FmodeApi, useValue: api },
- ],
- });
- const s2 = TestBed.inject(ChatSessionService);
- s2.load();
- return s2;
- }
- describe('ChatSessionService', () => {
- let svc: ChatSessionService;
- beforeEach(() => {
- localStorage.clear();
- TestBed.configureTestingModule({
- providers: [
- ChatSessionService,
- { provide: SessionService, useValue: { me: () => ({ id: 'u1' }) } },
- ],
- });
- svc = TestBed.inject(ChatSessionService);
- svc.reset();
- });
- afterEach(() => localStorage.clear());
- const ROOM = '!room1:fmode.cn';
- const AGENT = 'agent-a';
- it('新建会话:标题默认「新建对话」、未归档、计数 0', () => {
- const s = svc.create(ROOM, AGENT);
- expect(s.title).toBe('新建对话');
- expect(s.archived).toBeFalse();
- expect(s.messageCount).toBe(0);
- expect(s.roomId).toBe(ROOM);
- expect(s.agentId).toBe(AGENT);
- });
- it('create 生成独立线程根、同容器可并存多条', () => {
- const a = svc.create(ROOM, AGENT);
- const b = svc.create(ROOM, AGENT);
- expect(b.id).not.toBe(a.id);
- expect(svc.listFor(AGENT).length).toBe(2);
- });
- it('为什么服务端认为是同一个 agent 的不同容器 —— 会话互不可见', () => {
- svc.create(ROOM, 'agent-a');
- svc.create(ROOM, 'agent-b');
- expect(svc.listFor('agent-a').length).toBe(1);
- expect(svc.listFor('agent-b').length).toBe(1);
- });
- it('归档后默认列表不含它,但可按 id 取到(链接可打开)', () => {
- const s = svc.create(ROOM, AGENT);
- svc.archive(s.id);
- expect(svc.listFor(AGENT)).toEqual([]);
- expect(svc.listFor(AGENT, { includeArchived: true }).length).toBe(1);
- expect(svc.byId(s.id)?.archived).toBeTrue();
- });
- it('取消归档后回到列表', () => {
- const s = svc.create(ROOM, AGENT);
- svc.archive(s.id);
- svc.archive(s.id, false);
- expect(svc.listFor(AGENT).length).toBe(1);
- });
- it('重命名会锁定标题,之后消息不再覆盖', () => {
- const s = svc.create(ROOM, AGENT);
- svc.rename(s.id, ' 我的任务 ');
- const renamed = svc.byId(s.id)!;
- expect(renamed.title).toBe('我的任务');
- expect(renamed.titleLocked).toBeTrue();
- svc.noteMessage(s.id, { text: '新消息内容', ts: Date.now(), fromMe: true });
- expect(svc.byId(s.id)!.title).toBe('我的任务');
- });
- it('重命名空字符串被忽略', () => {
- const s = svc.create(ROOM, AGENT);
- svc.rename(s.id, ' ');
- // 未命名会话的默认标题是「新建对话」(2026-11-01 起)
- expect(svc.byId(s.id)!.title).toBe('新建对话');
- });
- it('用户首条消息推导标题', () => {
- const s = svc.create(ROOM, AGENT);
- svc.noteMessage(s.id, { text: '帮我做个登录页', ts: 2000, fromMe: true });
- expect(svc.byId(s.id)!.title).toBe('做个登录页');
- });
- describe('remove(用户主动移除)', () => {
- it('移除后从列表消失', () => {
- const s = svc.create(ROOM, AGENT);
- svc.remove(s.id);
- expect(svc.byId(s.id)).toBeUndefined();
- });
- it('🔴 移除的线程不会被下一次云端拉取复活', async () => {
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- {
- objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$gone',
- title: '被移除的对话', titleLocked: false, messageCount: 5,
- lastMessageAt: 100, archived: false, lastPreview: '',
- },
- ],
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- svc2.adopt({ id: '$gone', roomId: ROOM, agentId: AGENT });
- svc2.remove('$gone');
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId('$gone')).withContext('被移除的线程又回来了').toBeUndefined();
- });
- it('isRemoved 能查到移除记录', () => {
- const s = svc.create(ROOM, AGENT);
- expect(svc.isRemoved(s.id)).toBeFalse();
- svc.remove(s.id);
- expect(svc.isRemoved(s.id)).toBeTrue();
- });
- it('移除记录会持久化', () => {
- const s = svc.create(ROOM, AGENT);
- svc.remove(s.id);
- svc.reset();
- svc.load();
- expect(svc.isRemoved(s.id)).withContext('重载后黑名单丢了').toBeTrue();
- });
- });
- describe('历史对话(承接无 thread 旧消息)', () => {
- it('首次创建返回 created=true', () => {
- const r = svc.adoptLegacy(ROOM, AGENT, '旧消息预览');
- expect(r.created).toBeTrue();
- expect(r.session.id).toBe(legacySessionId(ROOM));
- expect(r.session.title).toBe('历史对话');
- expect(r.session.legacy).toBeTrue();
- expect(r.session.titleLocked).withContext('历史会话不改名').toBeTrue();
- });
- it('幂等:重复调用返回 created=false 且不重复添加', () => {
- svc.adoptLegacy(ROOM, AGENT);
- const again = svc.adoptLegacy(ROOM, AGENT);
- expect(again.created).toBeFalse();
- expect(svc.listFor(AGENT).length).toBe(1);
- });
- it('不同房间的历史会话 id 不同', () => {
- expect(legacySessionId('!a:x')).not.toBe(legacySessionId('!b:x'));
- });
- });
- describe('持久化', () => {
- it('新建后写入 localStorage(v2 缓存键,按用户隔离)', () => {
- const s = svc.create(ROOM, AGENT);
- const raw = localStorage.getItem('fmode_chat_sessions_v2_u1');
- expect(raw).withContext('未按用户隔离存储').toBeTruthy();
- expect(JSON.parse(raw!)[0].id).toBe(s.id);
- });
- it('重新载入能恢复会话', () => {
- const s = svc.create(ROOM, AGENT);
- svc.reset();
- svc.load();
- expect(svc.byId(s.id)).toBeDefined();
- });
- // 换账号不能看到上一个账号的会话
- it('🔴 换用户后不串号', () => {
- svc.create(ROOM, AGENT);
- expect(svc.all().length).toBe(1);
- // 切换成另一个用户
- TestBed.resetTestingModule();
- TestBed.configureTestingModule({
- providers: [
- ChatSessionService,
- { provide: SessionService, useValue: { me: () => ({ id: 'u2' }) } },
- ],
- });
- const other = TestBed.inject(ChatSessionService);
- other.load();
- expect(other.all()).withContext('读到了别人的会话').toEqual([]);
- });
- it('坏 JSON 不影响后续使用(降级为空列表)', () => {
- localStorage.setItem('fmode_chat_sessions_u1', '{{{ 不是 json');
- svc.reset();
- expect(() => svc.load()).not.toThrow();
- expect(svc.all()).toEqual([]);
- });
- it('缺字段的脏数据被过滤', () => {
- localStorage.setItem(
- 'fmode_chat_sessions_v2_u1',
- JSON.stringify([{ id: '$x' }, { id: '$ok', roomId: '!r:x', agentId: 'a', title: 't', createdAt: 1, updatedAt: 1 }]),
- );
- svc.reset();
- svc.load();
- expect(svc.all().length).toBe(1);
- expect(svc.all()[0].id).toBe('$ok');
- });
- });
- describe('threadIdsOf', () => {
- it('返回该房间下所有会话的线程根', () => {
- const a = svc.create(ROOM, AGENT);
- const b = svc.create(ROOM, 'agent-b');
- svc.create('!other:x', AGENT);
- const ids = svc.threadIdsOf(ROOM);
- expect(ids.has(a.id)).toBeTrue();
- expect(ids.has(b.id)).toBeTrue();
- expect(ids.size).toBe(2);
- });
- });
- describe('新建会话不被云端拉取冲掉(2026-11-01)', () => {
- const ROOM = '!room1:fmode.cn';
- const AGENT = 'agent-a';
- beforeEach(() => localStorage.clear());
- /*
- * 🔴 回归:点「新建对话」后,聊天区是新的但**左侧列表没有内容**。
- *
- * 根因:`create()` 之后是**异步**推云端的,而新建对话紧接着就换 URL
- * → 重新 `open()` → 又拉一次云端。那一刻云端列表里还没有这条,
- * `hydrateFromCloud` 按「云端没有就丢弃」处理,刚建出来的会话当场消失。
- */
- it('🔴 刚创建、还没推到云端的会话,不能被 hydrate 丢弃', async () => {
- let remote: unknown[] = [];
- const svc2 = withApiStub({
- // 云端暂时还没有这条(推送是异步的,这里模拟「推送还没落地」)
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted ? [] : remote,
- // upsert 永不 resolve —— 模拟推送尚未完成
- upsertChatThreads: () => new Promise<void>(() => undefined),
- });
- await svc2.hydrateFromCloud(AGENT);
- const s = svc2.create(ROOM, AGENT);
- // 换 URL 后重新拉云端(此时云端仍为空)
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId(s.id)).withContext('刚建的会话被云端拉取抹掉了').toBeDefined();
- });
- it('commit 落库后再拉取,以云端为准(标记已撤销)', async () => {
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- const s = svc2.create(ROOM, AGENT);
- svc2.commit(s.id);
- // 等推送 promise 落定
- await new Promise((r) => setTimeout(r, 10));
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId(s.id)).withContext('已落库但云端为空 → 说明已删除,应移除').toBeUndefined();
- });
- /*
- * 🔴 第二个回归:`pruneEmpty` 把刚建的会话当空壳删掉。
- *
- * 真实时序是「建会话 → 换 URL → 第二轮 onRouteChange → open() → pruneEmpty」,
- * 那一轮 keepId 可能还没指向它,于是刚建好的 0 条会话被当场清掉。
- */
- it('🔴 正在看的那条空会话不会被清理(keepId 保护)', async () => {
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- const s = svc2.create(ROOM, AGENT);
- // 用户正看着它 → 必须保留
- svc2.pruneEmpty(s.id);
- expect(svc2.byId(s.id)).withContext('当前会话被误删').toBeDefined();
- });
- /*
- * 🔴 用户反馈:多次新建对话后,前几次的都持久化/残留了。
- *
- * 规则是「**发过消息**才持久化」。从未落库的空会话(点了新建但没发消息)
- * 应当在切走时直接消失,不该留在列表里。
- */
- it('🔴 连点新建留下、且没发过消息的空会话,切走时全部清掉', async () => {
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- const a = svc2.create(ROOM, AGENT);
- const b = svc2.create(ROOM, AGENT);
- const c = svc2.create(ROOM, AGENT);
- // 用户切走到别的会话(c 被打开 → a、b 应被清掉)
- svc2.pruneEmpty(c.id);
- expect(svc2.byId(a.id)).withContext('未落库的空会话应被清掉').toBeUndefined();
- expect(svc2.byId(b.id)).toBeUndefined();
- expect(svc2.byId(c.id)).withContext('当前这条要保留').toBeDefined();
- });
- it('🔴 未落库的空会话被清理时,不向云端发删除请求', async () => {
- const remove = jasmine.createSpy('remove').and.returnValue(Promise.resolve());
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- removeChatThread: remove,
- });
- await svc2.hydrateFromCloud(AGENT);
- svc2.create(ROOM, AGENT);
- svc2.pruneEmpty(undefined);
- expect(remove).withContext('云端本来就没有这条,不该发删除请求').not.toHaveBeenCalled();
- });
- it('超过保护期的空壳仍会被清理(不会长期堆积)', async () => {
- /*
- * 保护期只针对「刚创建」的空会话(60 秒)。
- * 这里预先写入一条 61 秒前创建的空会话,它应该被正常清掉。
- * 直接写 localStorage 再 load,比 mock 系统时钟简单可靠。
- */
- const oldId = '$old:fmode.cn';
- localStorage.setItem(
- 'fmode_chat_sessions_v2_u1',
- JSON.stringify([
- {
- id: oldId, roomId: ROOM, agentId: AGENT, title: '旧空壳',
- createdAt: Date.now() - 61_000, updatedAt: 1, messageCount: 0, archived: false,
- },
- ]),
- );
- const svc2 = withApiStub({
- // 云端不可达 → 不会覆盖本地,能直接观察 pruneEmpty 的效果
- fetchChatThreads: async () => { throw new Error('offline'); },
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- svc2.pruneEmpty(undefined);
- expect(svc2.byId(oldId)).withContext('过期的空壳应该被清掉').toBeUndefined();
- });
- });
- describe('消息推进必须同步云端(2026-11-01)', () => {
- const ROOM = '!room1:fmode.cn';
- const AGENT = 'agent-a';
- beforeEach(() => localStorage.clear());
- /*
- * 🔴 回归:历史会话名称加载不对,显示成「新对话」。
- *
- * 根因:`noteMessage` 只写本地,标题/计数/时间从不推云端。
- * 云端那条记录永远停在「新对话 / 0 条」,换设备或重新拉列表就退回默认名。
- */
- it('🔴 首条消息确定标题后必须推送到云端', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: upsert,
- });
- await svc2.hydrateFromCloud(AGENT);
- const s = svc2.create(ROOM, AGENT);
- upsert.calls.reset();
- svc2.noteMessage(s.id, { text: '帮我做个登录页', ts: Date.now(), fromMe: true });
- expect(upsert).withContext('标题变了必须推云端,否则换设备退回「新对话」').toHaveBeenCalled();
- const pushed = upsert.calls.mostRecent().args[0][0];
- expect(pushed.title).toBe('做个登录页');
- expect(pushed.threadRoot).toBe(s.id);
- });
- it('同一会话短时间内重复消息不重复打接口(节流)', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: upsert,
- });
- await svc2.hydrateFromCloud(AGENT);
- const s = svc2.create(ROOM, AGENT);
- /*
- * 2026-11-01:`create()` 只建本地,**未落库**的会话在 noteMessage 里
- * 不参与节流(必须立刻写)。这里先 commit 让它进入「已落库」状态,
- * 才能验证节流本身。
- */
- svc2.commit(s.id);
- await new Promise((r) => setTimeout(r, 10));
- upsert.calls.reset();
- // 首条定标题(触发一次)
- svc2.noteMessage(s.id, { text: '第一条', ts: 1000, fromMe: true });
- const afterFirst = upsert.calls.count();
- // 紧随其后的几条只改计数,不应再推
- svc2.noteMessage(s.id, { text: '第二条', ts: 1001, fromMe: true });
- svc2.noteMessage(s.id, { text: '第三条', ts: 1002, fromMe: true });
- expect(upsert.calls.count()).withContext('计数变化不该每条都打接口').toBe(afterFirst);
- });
- });
- describe('工作区归属(2026-11-01 上云)', () => {
- const ROOM = '!room1:fmode.cn';
- const AGENT = 'agent-a';
- const WS = 'ws-1';
- beforeEach(() => localStorage.clear());
- /*
- * 🔴 回归:用户反馈「在工作区里新建对话,结果跑到下面日常对话里去了」。
- *
- * 根因:归属只存本地,`hydrateFromCloud` 重建列表时靠本地缓存「捡」,
- * 捡不到就回落 null(日常)。现在云端是权威来源。
- */
- it('🔴 云端返回的 workspaceId 必须覆盖本地为空的归属', async () => {
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$w', title: 't', titleLocked: false, messageCount: 2, lastMessageAt: 9, archived: false, lastPreview: '', workspaceId: WS },
- ],
- upsertChatThreads: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId('$w')?.workspaceId).withContext('归属丢了会掉进日常对话').toBe(WS);
- });
- it('moveTo 会把归属推到云端(用 upsert,云端可能还没这条)', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$w', title: 't', titleLocked: false, messageCount: 2, lastMessageAt: 9, archived: false, lastPreview: '' },
- ],
- upsertChatThreads: upsert,
- });
- await svc2.hydrateFromCloud(AGENT);
- svc2.moveTo('$w', WS);
- /*
- * 🔴 必须是 upsert 而不是 patch:
- * 「新建对话 → 立刻移动工作区」时云端可能还没有这条记录,
- * patch 会返回 404 被当成成功,归属压根没写进云端。
- */
- expect(upsert)
- .withContext('云端可能还没这条,必须用 upsert')
- .toHaveBeenCalledWith(
- jasmine.arrayContaining([jasmine.objectContaining({ threadRoot: '$w', workspaceId: WS })]),
- );
- expect(svc2.byId('$w')?.workspaceId).toBe(WS);
- });
- it('移回日常对话时云端收到空字符串(不是不传)', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApiStub({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$w', title: 't', titleLocked: false, messageCount: 2, lastMessageAt: 9, archived: false, lastPreview: '', workspaceId: WS },
- ],
- upsertChatThreads: upsert,
- });
- await svc2.hydrateFromCloud(AGENT);
- svc2.moveTo('$w', null);
- expect(upsert).toHaveBeenCalledWith(
- jasmine.arrayContaining([jasmine.objectContaining({ threadRoot: '$w', workspaceId: '' })]),
- );
- expect(svc2.byId('$w')?.workspaceId).toBeNull();
- });
- });
- describe('云端会话目录(2026-11-01 单向同步)', () => {
- const ROOM = '!room1:fmode.cn';
- const AGENT = 'agent-a';
- beforeEach(() => localStorage.clear());
- /** 以「带 FmodeApi 桩」的方式重建服务(内部用;原 `withApi` 已改为文件级 `withApiStub`) */
- function withApi(api: Record<string, unknown>): ChatSessionService {
- return withApiStub(api);
- }
- it('云端有新会话、本地为空 → 重建到本地(换浏览器场景)', async () => {
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- {
- objectId: 'x1', agentId: AGENT, roomId: ROOM, threadRoot: '$cloud1',
- title: '云端会话', titleLocked: false, messageCount: 3,
- lastMessageAt: 1000, archived: false, lastPreview: 'hi',
- },
- ],
- upsertChatThreads: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId('$cloud1')?.title).toBe('云端会话');
- expect(svc2.byId('$cloud1')?.messageCount).toBe(3);
- });
- it('已移除的线程不会被云端复活', async () => {
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$gone', title: 'a', titleLocked: false, messageCount: 1, lastMessageAt: 1, archived: false, lastPreview: '' },
- ],
- upsertChatThreads: async () => undefined,
- removeChatThread: async () => undefined,
- });
- const s0 = svc2.create(ROOM, AGENT);
- svc2.remove(s0.id);
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId(s0.id)).toBeUndefined();
- });
- /*
- * 🔴 行为变更(2026-11-01):单向同步下**云端标题才是权威**。
- *
- * 旧断言「本地锁定标题不被云端覆盖」在合并式同步下成立,但正是它允许了
- * 「本地与云端各说各话」——改名推云端失败后,本地会永远保留一个云端不知道的标题。
- * 现在:改名会立刻 `patchChatThread` 推云端,云端成功后自然以云端为准;
- * `titleLocked` 只用于防止「首条消息自动命名」覆盖用户手动改过的名字。
- */
- it('改名成功后标题以云端为准', async () => {
- let remoteTitle = '云端标题';
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$t', title: remoteTitle, titleLocked: true, messageCount: 1, lastMessageAt: 5, archived: false, lastPreview: '' },
- ],
- upsertChatThreads: async () => undefined,
- patchChatThread: async (i: { title?: string }) => {
- if (i.title) remoteTitle = i.title;
- },
- });
- svc2.adopt({ id: '$t', roomId: ROOM, agentId: AGENT });
- svc2.rename('$t', '我改的标题');
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId('$t')?.title).withContext('云端已更新,应展示新标题').toBe('我改的标题');
- });
- it('归档状态以云端为准', async () => {
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) =>
- o?.includeDeleted
- ? []
- : [
- { objectId: 'x', agentId: AGENT, roomId: ROOM, threadRoot: '$a', title: 't', titleLocked: false, messageCount: 1, lastMessageAt: 9, archived: true, lastPreview: '' },
- ],
- upsertChatThreads: async () => undefined,
- });
- svc2.adopt({ id: '$a', roomId: ROOM, agentId: AGENT });
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.byId('$a')?.archived).toBeTrue();
- });
- it('🔴 云端明确为空 → 本机**已落库**的会话一并清掉(删除后不再复活)', async () => {
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- });
- const s = svc2.create(ROOM, AGENT);
- /*
- * 2026-11-01:`create()` 只建本地、不落库,且带 `_pendingPush` 保护 ——
- * 云端为空时它会被保留(否则新建对话刚建出来就被抹掉)。
- * 这里模拟「已经落库完成」的会话,验证云端删除仍能正常生效。
- */
- svc2.commit(s.id);
- await new Promise((r) => setTimeout(r, 0));
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.listFor(AGENT, { includeArchived: true }).length).toBe(0);
- });
- it('云端为空时不误推本地会话(新建的未落库会话除外)', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: upsert,
- });
- /*
- * 2026-11-01:`create()` 已不再推云端(本地先建、首条消息才落库),
- * 所以这里验证的是「pushAll 不会被调用去灌云端」。
- * 未落库的新会话由 commit() 负责,不属于 pushAll 的职责。
- */
- await svc2.hydrateFromCloud(AGENT);
- await svc2.pushAll(AGENT);
- expect(upsert.calls.count()).withContext('云端为空时不该推任何东西').toBe(0);
- });
- /*
- * 🔴 行为变更(2026-11-01 用户裁决):云端不可达时**列表不可信**。
- *
- * 旧行为「保留本地缓存照常展示」看着更"稳",实际是两端互相覆盖的根源:
- * 用户看到的可能是几小时前的列表,在上面做的删除/归档又会回写云端。
- */
- it('🔴 云端不可达 → ready=false,界面据此显示「加载失败」', async () => {
- const svc2 = withApi({
- fetchChatThreads: async () => { throw new Error('network'); },
- upsertChatThreads: async () => { throw new Error('network'); },
- });
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.ready()).toBeFalse();
- expect(svc2.error()).toBe('network');
- });
- it('云端不可达时 pushAll 不推送(列表本身就不可信)', async () => {
- const upsert = jasmine.createSpy('upsert').and.returnValue(Promise.resolve());
- const svc2 = withApi({
- fetchChatThreads: async () => { throw new Error('network'); },
- upsertChatThreads: upsert,
- });
- svc2.create(ROOM, AGENT);
- const before = upsert.calls.count();
- await svc2.hydrateFromCloud(AGENT);
- await svc2.pushAll(AGENT);
- expect(upsert.calls.count()).withContext('云端不可达时不应回写').toBe(before);
- });
- it('云端成功返回后 ready=true', async () => {
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : []),
- upsertChatThreads: async () => undefined,
- });
- expect(svc2.ready()).toBeFalse();
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.ready()).toBeTrue();
- });
- it('🔴 云端删掉的会话,本地下一次拉取即消失', async () => {
- let live = [
- { objectId: 'a', agentId: AGENT, roomId: ROOM, threadRoot: '$a', title: 'A', titleLocked: false, messageCount: 1, lastMessageAt: 1, archived: false, lastPreview: '' },
- { objectId: 'b', agentId: AGENT, roomId: ROOM, threadRoot: '$b', title: 'B', titleLocked: false, messageCount: 1, lastMessageAt: 2, archived: false, lastPreview: '' },
- ];
- const svc2 = withApi({
- fetchChatThreads: async (_a: string, o?: { includeDeleted?: boolean }) => (o?.includeDeleted ? [] : live),
- upsertChatThreads: async () => undefined,
- });
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.listFor(AGENT).length).toBe(2);
- live = [live[0]];
- await svc2.hydrateFromCloud(AGENT);
- expect(svc2.listFor(AGENT).map((s) => s.id)).withContext('云端没有的应被移除').toEqual(['$a']);
- });
- });
- });
|