Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(chat): 支持长期可重复的群邀请与单链接撤销 (#5674)

Chris Zhangf3225d079881
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatInviteRevokeIpcSecurity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatInviteRevokeIpcSecurity.test.ts
new file mode 100644
index 0000000000..812c764e97
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatInviteRevokeIpcSecurity.test.ts
@@ -0,0 +1,67 @@
+import { readFileSync } from 'node:fs';
+import { ScriptTarget, transpileModule } from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { MAKER_INVOKE } from '../channels';
+
+// Execute the production registration with fake Electron dependencies, without
+// starting Desktop or duplicating the handler's security checks in the test.
+const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+const start = source.indexOf('ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_REVOKEINVITE,');
+const end = source.indexOf('ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_ACCEPTINVITE,', start);
+if (start < 0 || end <= start) throw new Error('invite revoke registration not found');
+const compiled = transpileModule(source.slice(start, end), {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+}).outputText;
+
+const input = {
+ groupId: '00000000-0000-4000-8000-000000000001',
+ link: `cindy://chat-invite/${'a'.repeat(43)}`,
+ clientId: '00000000-0000-4000-8000-000000000002',
+};
+const trustedSender = {};
+type Handler = (event: { sender: object }, payload: typeof input) => Promise<unknown>;
+
+function bridge(ready = true) {
+ const handlers = new Map<string, Handler>();
+ const guard = vi.fn((event: { sender: object }) => {
+ if (event.sender !== trustedSender) throw Object.assign(new Error('untrusted sender'), { code: 'PERMISSION_DENIED' });
+ });
+ const revokeInvite = vi.fn().mockResolvedValue({ ok: true, revoked: true });
+ const readService = vi.fn(() => ({ revokeInvite }));
+ const deps = {
+ ipcMain: { handle: (channel: string, handler: Handler) => handlers.set(channel, handler) },
+ MAKER_INVOKE,
+ assertTrustedAppRendererEvent: guard,
+ botGroupChatServiceHolder: ready ? { get chatServer() { return readService(); } } : null,
+ };
+ new Function(...Object.keys(deps), compiled)(...Object.values(deps));
+ expect([...handlers.keys()]).toEqual([MAKER_INVOKE.CHAT_SERVER_REVOKEINVITE]);
+ return { guard, revokeInvite, readService, invoke: handlers.get(MAKER_INVOKE.CHAT_SERVER_REVOKEINVITE)! };
+}
+
+describe('invitation revoke IPC sender boundary', () => {
+ it('rejects an untrusted sender before accessing or calling the revocation service', async () => {
+ const api = bridge();
+ const event = { sender: {}, trusted: true };
+ await expect(api.invoke(event, input)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(api.guard).toHaveBeenCalledWith(event);
+ expect(api.readService).not.toHaveBeenCalled();
+ expect(api.revokeInvite).not.toHaveBeenCalled();
+ });
+
+ it('delegates the unchanged request from a trusted sender', async () => {
+ const api = bridge();
+ const event = { sender: trustedSender };
+ await expect(api.invoke(event, input)).resolves.toEqual({ ok: true, revoked: true });
+ expect(api.guard).toHaveBeenCalledWith(event);
+ expect(api.guard.mock.invocationCallOrder[0]).toBeLessThan(api.readService.mock.invocationCallOrder[0]);
+ expect(api.revokeInvite).toHaveBeenCalledExactlyOnceWith(input);
+ });
+
+ it('checks the sender even when the host is not ready, then returns its fallback for a trusted sender', async () => {
+ const api = bridge(false);
+ await expect(api.invoke({ sender: {} }, input)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ await expect(api.invoke({ sender: trustedSender }, input)).resolves.toEqual({ ok: false, errorCode: 'HOST_NOT_READY' });
+ expect(api.revokeInvite).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerInvitations.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerInvitations.test.ts
new file mode 100644
index 0000000000..00ca0d28f1
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerInvitations.test.ts
@@ -0,0 +1,166 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const fixture = vi.hoisted(() => ({ download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), refresh: vi.fn(async () => true), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[] }));
+vi.mock('../../authManager.js', () => ({ getAccessToken: () => 'isolated-test-token', refresh: fixture.refresh }));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
+vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: vi.fn(async () => []), download: fixture.download }) }));
+vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('electron', () => ({ app: { get isPackaged() { return fixture.packaged; }, getPath: () => '/isolated' } }));
+vi.mock('node:fs', () => ({ existsSync: fixture.exists, readFileSync: () => fixture.config || '{"baseUrl":"https://example.com","token":"test"}' }));
+vi.mock('../botGroupChatService.js', () => ({ readPersistedReplyText: vi.fn() }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: {
+ select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve(fixture.profiles), { limit: async () => [{ id: 'existing-local-group' }] }) }) }),
+ insert: () => ({ values: () => ({ onConflictDoNothing: async () => undefined }) }),
+} }) }));
+vi.mock('node:http', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { request: (url: string, options: { method: string; headers: Record<string, string> }, callback: (response: unknown) => void) => {
+ fixture.urls.push(String(url));
+ const req = Object.assign(new EventEmitter(), {
+ end: (data?: string) => {
+ void Promise.resolve().then(() => fixture.handle(new URL(url).pathname.slice(3) + new URL(url).search, options.method, data ? JSON.parse(data) : undefined, options.headers))
+ .then(result => {
+ const response = Object.assign(new EventEmitter(), { statusCode: result?.status ?? 200, headers: result?.headers ?? {} });
+ callback(response);
+ response.emit('data', Buffer.from(result?.raw ?? JSON.stringify(result?.body ?? {})));
+ response.emit('end');
+ }, error => req.emit('error', error));
+ },
+ destroy: (error: Error) => req.emit('error', error),
+ });
+ return req;
+ } };
+});
+vi.mock('node:https', async () => ({ request: (await import('node:http')).request }));
+vi.mock('ws', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { default: class extends EventEmitter {
+ static OPEN = 1; readyState = 0; send = vi.fn();
+ constructor(url: URL) { super(); fixture.wsUrls.push(String(url)); fixture.sockets.push(this as unknown as import('ws').WebSocket); }
+ close() { this.emit('close'); }
+ } };
+});
+import { withChatServer } from '../chatServer.js';
+import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';
+
+describe('Chat Server invitation contract', () => {
+ const groupId = '10000000-0000-4000-8000-000000000001';
+ const selfId = '30000000-0000-4000-8000-000000000001';
+ const token = 'a'.repeat(43);
+ const link = `cindy://chat-invite/${token}`;
+ const clientId = '40000000-0000-4000-8000-000000000001';
+ let service: BotGroupChatService;
+ let expiresAt: unknown;
+ let reusable: boolean | undefined;
+ let members: unknown[];
+ beforeEach(() => {
+ fixture.packaged = true; fixture.profiles = []; fixture.sockets = [];
+ expiresAt = null; reusable = true;
+ members = [{ id: selfId, ownerActorId: selfId, state: 'joined', role: 'owner' }];
+ fixture.handle.mockImplementation(route => {
+ if (route === '/me') return { body: { actor: { id: selfId } } };
+ if (route.endsWith('/snapshot')) return { body: { members } };
+ if (route === `/conversations/${groupId}/invite-links`) return { body: { token, expiresAt, ...(reusable !== undefined ? { reusable } : {}) } };
+ if (route === '/invite-links/preview') return { body: { groupId, name: 'Group', inviterName: 'Host', expiresAt, ...(reusable !== undefined ? { reusable } : {}), joined: false } };
+ if (route.endsWith('/invite-links/revoke')) return { body: { revoked: true } };
+ return { body: [] };
+ });
+ service = withChatServer({ dispose: vi.fn() } as unknown as BotGroupChatService, {} as BotGroupChatServiceDeps);
+ });
+ afterEach(() => { service.dispose(); vi.clearAllMocks(); });
+ it.each([[null, true], ['2026-10-10T12:00:00.000Z', false], ['2026-10-10T12:00:00.000Z', undefined]] as const)('preserves expiry %s / reusable %s across creation and preview', async (value, reuse) => {
+ expiresAt = value; reusable = reuse;
+ expect(await service.chatServer!.createInvite({ groupId, clientId })).toEqual({ ok: true, link, expiresAt, ...(reusable !== undefined ? { reusable } : {}) });
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: true, groupId, name: 'Group', inviterName: 'Host', expiresAt, ...(reusable !== undefined ? { reusable } : {}), joined: false });
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${groupId}/invite-links`, 'POST', { operationId: clientId }, expect.objectContaining({ 'X-Chat-Actor': selfId }));
+ });
+ it.each([undefined, '', 'bad-date', 123])('rejects invalid expiry %s instead of calling it permanent', async value => {
+ expiresAt = value;
+ expect((await service.chatServer!.createInvite({ groupId, clientId })).ok).toBe(false);
+ expect((await service.chatServer!.previewInvite({ link })).ok).toBe(false);
+ });
+ it.each([undefined, false])('does not accept a null expiry without reusable=true (%s)', async flag => {
+ reusable = flag;
+ expect(await service.chatServer!.createInvite({ groupId, clientId })).toEqual({ ok: false, errorCode: 'CHAT_RESPONSE_INVALID' });
+ });
+ it('preserves server denial and never accepts an invitation during preview', async () => {
+ fixture.handle.mockImplementation(route => route === '/invite-links/preview'
+ ? { status: 404, body: { error: { code: 'INVITATION_NOT_FOUND' } } } : { body: [] });
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: false, errorCode: 'INVITATION_NOT_FOUND' });
+ expect(fixture.handle.mock.calls.some(([route]) => route === '/invite-links/accept')).toBe(false);
+ });
+ it('sends only the current token and group under the management actor, preserving retry id', async () => {
+ const input = { groupId, link, clientId };
+ expect(await service.chatServer!.revokeInvite(input)).toEqual({ ok: true, revoked: true });
+ expect(await service.chatServer!.revokeInvite(input)).toEqual({ ok: true, revoked: true });
+ const calls = fixture.handle.mock.calls.filter(([route]) => route.endsWith('/invite-links/revoke'));
+ expect(calls).toHaveLength(2);
+ expect(calls[0]).toEqual([`/conversations/${groupId}/invite-links/revoke`, 'POST', { token, operationId: clientId }, expect.objectContaining({ 'X-Chat-Actor': selfId })]);
+ expect(calls[1]).toEqual(calls[0]);
+ });
+ it.each(['member', 'left', 'foreign'])('does not send a revoke request without management rights: %s', async kind => {
+ members = [{ id: selfId, ownerActorId: kind === 'foreign' ? groupId : selfId, state: kind === 'left' ? 'left' : 'joined', role: kind === 'member' ? 'member' : 'owner' }];
+ expect(await service.chatServer!.revokeInvite({ groupId, link, clientId })).toEqual({ ok: false, errorCode: 'ROLE_REQUIRED' });
+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/revoke'))).toBe(false);
+ });
+ it('allows the account to manage through its owner teammate actor', async () => {
+ members = [{ id: groupId, ownerActorId: selfId, state: 'joined', role: 'admin' }];
+ expect((await service.chatServer!.revokeInvite({ groupId, link, clientId })).ok).toBe(true);
+ expect(fixture.handle.mock.calls.find(([route]) => route.endsWith('/revoke'))?.[3]).toMatchObject({ 'X-Chat-Actor': groupId });
+ });
+ it.each([
+ [403, { error: { code: 'ROLE_REQUIRED' } }, 'ROLE_REQUIRED'],
+ [404, { error: { code: 'INVITATION_NOT_FOUND' } }, 'INVITATION_NOT_FOUND'],
+ [404, {}, 'INVITE_REVOKE_UNSUPPORTED'],
+ [200, {}, 'CHAT_RESPONSE_INVALID'],
+ [200, { revoked: false }, 'CHAT_RESPONSE_INVALID'],
+ [201, { revoked: true }, 'CHAT_RESPONSE_INVALID'],
+ ])('keeps rejection at status %s as failure (%s)', async (status, body, errorCode) => {
+ const original = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route.endsWith('/revoke') ? { status, body } : original(route, ...args));
+ expect(await service.chatServer!.revokeInvite({ groupId, link, clientId })).toEqual({ ok: false, errorCode });
+ });
+ it('recognizes the old server non-JSON 404 without claiming success', async () => {
+ const original = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route.endsWith('/revoke') ? { status: 404, raw: '<html>Not found</html>' } : original(route, ...args));
+ expect(await service.chatServer!.revokeInvite({ groupId, link, clientId })).toEqual({ ok: false, errorCode: 'INVITE_REVOKE_UNSUPPORTED' });
+ });
+ it.each([200, 201])('keeps the exact revocation success status after refreshing an expired token (status %s)', async status => {
+ const original = fixture.handle.getMockImplementation()!;
+ let attempts = 0;
+ fixture.handle.mockImplementation((route, ...args) => {
+ if (!route.endsWith('/revoke')) return original(route, ...args);
+ return ++attempts === 1 ? { status: 401, body: { error: { code: 'TOKEN_EXPIRED' } } } : { status, body: { revoked: true } };
+ });
+ expect(await service.chatServer!.revokeInvite({ groupId, link, clientId })).toEqual(status === 200
+ ? { ok: true, revoked: true } : { ok: false, errorCode: 'CHAT_RESPONSE_INVALID' });
+ expect(fixture.refresh).toHaveBeenCalledOnce();
+ const calls = fixture.handle.mock.calls.filter(([route]) => route.endsWith('/revoke'));
+ expect(calls).toHaveLength(2);
+ expect(calls[1]).toEqual(calls[0]);
+ });
+ it('shares the authentication refresh cooldown across repeated invitation failures', async () => {
+ const original = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route === '/invite-links/preview'
+ ? { status: 401, body: { error: { code: 'TOKEN_EXPIRED' } } } : original(route, ...args));
+ for (let i = 0; i < 2; i++) {
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: false, errorCode: 'TOKEN_EXPIRED' });
+ }
+ expect(fixture.refresh).toHaveBeenCalledOnce();
+ });
+ it.each(['ACCOUNT_INACTIVE', 'ROLE_REQUIRED'])('does not refresh a non-refreshable invitation rejection (%s)', async errorCode => {
+ fixture.handle.mockResolvedValue({ status: 401, body: { error: { code: errorCode } } });
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: false, errorCode });
+ expect(fixture.refresh).not.toHaveBeenCalled();
+ });
+ it('does not refresh a malformed 401 invitation response', async () => {
+ fixture.handle.mockResolvedValue({ status: 401, raw: '<html>auth challenge fixture</html>' });
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: false, errorCode: 'REQUEST_FAILED' });
+ expect(fixture.refresh).not.toHaveBeenCalled();
+ });
+ it('returns a sanitized failure for malformed invite responses', async () => {
+ fixture.handle.mockResolvedValue({ raw: 'not-json-containing-an-invitation-token' });
+ expect(await service.chatServer!.previewInvite({ link })).toEqual({ ok: false, errorCode: 'CHAT_RESPONSE_INVALID' });
+ });
+
+});
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index b61d52af5f..92a38ef184 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -788,6 +788,7 @@ export const MAKER_INVOKE = {
CHAT_SERVER_REPLY: 'maker:chat-server:reply',
CHAT_SERVER_REACT: 'maker:chat-server:react',
CHAT_SERVER_CREATEINVITE: 'maker:chat-server:createInvite',
+ CHAT_SERVER_REVOKEINVITE: 'maker:chat-server:revokeInvite',
CHAT_SERVER_PREVIEWINVITE: 'maker:chat-server:previewInvite',
CHAT_SERVER_ACCEPTINVITE: 'maker:chat-server:acceptInvite',
BOT_GROUP_LIST: 'maker:bot-group:list',
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index de0d61b3dc..8911831d16 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -26,7 +26,7 @@ import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';
import { untrustedJsonBlock } from '../../shared/untrustedPrompt.js';
import {
BOT_GROUP_CLIENT_ID, isBotGroupNoReplyText,
- type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi, type ChatInvitePreview,
+ type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
} from '../../shared/botGroupChat.js';
import type { BotGroupChatService, BotGroupChatServiceDeps, BotGroupLaneTerminal } from './botGroupChatService.js';
import { readPersistedReplyText } from './botGroupChatService.js';
@@ -178,7 +178,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
authRefreshPromise = refresh().finally(() => { authRefreshPromise = undefined; });
return authRefreshPromise;
}
- function api<T>(route: string, method = 'GET', data?: unknown, actorId?: string, retried = false): Promise<T> {
+ function api<T>(route: string, method = 'GET', data?: unknown, actorId?: string, retried = false, successStatus?: number): Promise<T> {
if (!current()) return Promise.reject(new Error('OWNER_CHANGED'));
if (!config.baseUrl) return Promise.reject(new Error('CHAT_ENDPOINT_UNAVAILABLE'));
const url = new URL(`${config.baseUrl}/v1${route}`);
@@ -207,12 +207,18 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
} }) : undefined;
let value;
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
- catch { throw new ChatResponseError('INVALID_CHAT_RESPONSE', status >= 400 ? status : 502, retryAt); }
+ catch {
+ // Older servers may return a non-JSON 404 for an unknown route.
+ if (successStatus && status >= 400) throw new ChatResponseError('REQUEST_FAILED', status, retryAt);
+ if (successStatus) throw new Error('CHAT_RESPONSE_INVALID');
+ throw new ChatResponseError('INVALID_CHAT_RESPONSE', status >= 400 ? status : 502, retryAt);
+ }
const code = typeof value?.error?.code === 'string' ? value.error.code : 'REQUEST_FAILED';
if (res.statusCode === 401 && !retried && CHAT_REFRESHABLE_ERROR_CODES.has(code)) {
- if (await refreshRejectedToken(token) && current()) { resolve(api<T>(route, method, data, actorId, true)); return; }
+ if (await refreshRejectedToken(token) && current()) { resolve(api<T>(route, method, data, actorId, true, successStatus)); return; }
}
if (status >= 400) throw new ChatResponseError(code, status, retryAt);
+ if (successStatus && status !== successStatus) throw new Error('CHAT_RESPONSE_INVALID');
resolve(value);
} catch (error) { reject(error); }
});
@@ -878,6 +884,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const inviteToken = (link: string) => z.string().regex(/^[A-Za-z0-9_-]{43}$/).parse(
z.string().max(100).parse(link).trim().replace(/^cindy:\/\/chat-invite\//, ''),
);
+ // Null is the server's non-expiring contract; omitted/invalid dates are never
+ // treated as permanent links. Older servers keep their dated, single-use links.
+ const inviteExpiry = z.string().refine(value => Number.isFinite(Date.parse(value))).nullable();
+ const inviteFields = { expiresAt: inviteExpiry, reusable: z.boolean().optional() };
+ const validInvite = (value: { expiresAt: string | null; reusable?: boolean }) => value.expiresAt !== null || value.reusable === true;
+ const invitePreview = z.object({ groupId: id, name: z.string(), inviterName: z.string(), ...inviteFields, joined: z.boolean() }).refine(validInvite);
+ function inviteResponse<T>(schema: z.ZodType<T>, value: unknown): T {
+ const parsed = schema.safeParse(value);
+ if (!parsed.success) throw new Error('CHAT_RESPONSE_INVALID');
+ return parsed.data;
+ }
const operationId = z.string().min(8).max(160).regex(/^[a-zA-Z0-9_.:-]+$/);
const chatServer: ChatServerApi = {
ownedBots: () => result(async () => { await register(); return { bots: actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active').map(a => ({ actorId: a.id, name: a.name })) }; }),
@@ -931,10 +948,24 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}),
createInvite: input => result(async () => {
const i = z.object({ groupId: id, clientId: operationId }).parse(input);
- const invite = await api<{ token: string; expiresAt: string }>(`/conversations/${i.groupId}/invite-links`, 'POST', { operationId: i.clientId }, managementActor(await snapshot(i.groupId)));
- return { link: `cindy://chat-invite/${invite.token}`, expiresAt: invite.expiresAt };
+ const invite = inviteResponse(z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{43}$/), ...inviteFields }).refine(validInvite),
+ await api(`/conversations/${i.groupId}/invite-links`, 'POST', { operationId: i.clientId }, managementActor(await snapshot(i.groupId)), false, 200),
+ );
+ return { link: `cindy://chat-invite/${invite.token}`, expiresAt: invite.expiresAt, ...(invite.reusable !== undefined ? { reusable: invite.reusable } : {}) };
+ }),
+ revokeInvite: input => result(async () => {
+ const i = z.object({ groupId: id, link: z.string(), clientId: z.string().uuid() }).strict().parse(input);
+ const token = inviteToken(i.link);
+ const actor = managementActor(await snapshot(i.groupId));
+ if (!actor) throw new Error('ROLE_REQUIRED');
+ try {
+ return inviteResponse(z.object({ revoked: z.literal(true) }), await api(`/conversations/${i.groupId}/invite-links/revoke`, 'POST', { token, operationId: i.clientId }, actor, false, 200));
+ } catch (error) {
+ if (error instanceof ChatResponseError && error.status === 404 && ['REQUEST_FAILED', 'NOT_FOUND'].includes(error.message)) throw new Error('INVITE_REVOKE_UNSUPPORTED');
+ throw error;
+ }
}),
- previewInvite: input => result(async () => api<ChatInvitePreview>('/invite-links/preview', 'POST', { token: inviteToken(input.link) })),
+ previewInvite: input => result(async () => inviteResponse(invitePreview, await api('/invite-links/preview', 'POST', { token: inviteToken(input.link) }, undefined, false, 200))),
acceptInvite: input => result(async () => {
const room = await api<{ groupId: string }>('/invite-links/accept', 'POST', { token: inviteToken(input.link), operationId: operationId.parse(input.clientId) });
rooms.delete(room.groupId); subscribe(room.groupId); changed(room.groupId); return room;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c164034091..282deea7e8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10877,6 +10877,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const chat = botGroupChatServiceHolder?.chatServer;
return chat ? chat.previewInvite(input) : { ok: false, errorCode: 'HOST_NOT_READY' };
});
+ ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_REVOKEINVITE, async (event, input) => {
+ assertTrustedAppRendererEvent(event);
+ const chat = botGroupChatServiceHolder?.chatServer;
+ return chat ? chat.revokeInvite(input) : { ok: false, errorCode: 'HOST_NOT_READY' };
+ });
ipcMain.handle(MAKER_INVOKE.CHAT_SERVER_ACCEPTINVITE, async (event, input) => {
assertTrustedAppRendererEvent(event);
const chat = botGroupChatServiceHolder?.chatServer;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f73d6760a6..acb7f179dc 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5966,6 +5966,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:chat-server:react', input),
createInvite: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['createInvite']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['createInvite']> =>
ipcRenderer.invoke('maker:chat-server:createInvite', input),
+ revokeInvite: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['revokeInvite']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['revokeInvite']> =>
+ ipcRenderer.invoke('maker:chat-server:revokeInvite', input),
previewInvite: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['previewInvite']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['previewInvite']> =>
ipcRenderer.invoke('maker:chat-server:previewInvite', input),
acceptInvite: (input: Parameters<import('../shared/botGroupChat').ChatServerApi['acceptInvite']>[0]): ReturnType<import('../shared/botGroupChat').ChatServerApi['acceptInvite']> =>
diff --git a/apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx b/apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx
index 24a0df778d..7656314413 100644
--- a/apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx
@@ -3,6 +3,7 @@ import * as Dialog from '@radix-ui/react-dialog';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
import type { ChatInvitePreview } from '../../../shared/botGroupChat';
@@ -13,41 +14,98 @@ const key = (name: string) => `bots.groupChat.server.${name}`;
const api = () => window.electronAPI.maker.chatServer;
export function ChatInviteDialog({ groupId, initialLink = '', onClose, onJoined }: { groupId?: string; initialLink?: string; onClose: () => void; onJoined?: (id: string) => void }) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const [link, setLink] = useState(initialLink);
+ const [expiresAt, setExpiresAt] = useState<string | null | undefined>();
+ const [reusable, setReusable] = useState<boolean | undefined>();
+ const [revoked, setRevoked] = useState(false);
+ const [revokeConfirm, setRevokeConfirm] = useState(false);
+ const [revokeUnsupported, setRevokeUnsupported] = useState(false);
+ const [now, setNow] = useState(Date.now());
const [preview, setPreview] = useState<ChatInvitePreview | null>(null);
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const mounted = useRef(true);
const operation = useRef(crypto.randomUUID());
+ const revokeOperation = useRef(crypto.randomUUID());
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
- async function run() {
+ const expiry = groupId ? expiresAt : preview?.expiresAt;
+ const expired = typeof expiry === 'string' && Date.parse(expiry) <= now;
+ useEffect(() => {
+ if (groupId && link && expired) operation.current = crypto.randomUUID();
+ }, [groupId, link, expired]);
+ useEffect(() => {
+ if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return;
+ const remaining = Date.parse(expiry) - Date.now();
+ if (remaining <= 0) return;
+ const timer = setTimeout(() => setNow(Date.now()), Math.min(remaining, 2_147_483_647));
+ return () => clearTimeout(timer);
+ }, [expiry, now]);
+ const validity = revoked ? t(key('revokedLink'))
+ : expiry === null && (groupId ? reusable : preview?.reusable) === true ? t(key('reusableLink'))
+ : expired ? t(key('expiredLink'))
+ : typeof expiry === 'string' && Number.isFinite(Date.parse(expiry))
+ ? t(key('singleUseUntil'), { date: new Date(expiry).toLocaleString(i18n.language) }) : '';
+ const canRevoke = reusable !== undefined && typeof api().revokeInvite === 'function' && !revokeUnsupported;
+ async function run(action: 'main' | 'revoke' | 'copy' = 'main') {
if (busyRef.current) return;
busyRef.current = true; setBusy(true); setError('');
const owner = getDataOwnerGeneration();
const current = () => mounted.current && isDataOwnerGenerationCurrent(owner);
try {
- if (groupId) {
+ if (action === 'copy') {
+ if (expired || (typeof expiry === 'string' && Date.parse(expiry) <= Date.now()) || revoked || !link) return;
+ await navigator.clipboard.writeText(link);
+ if (current()) toast.success(t(key('copied')));
+ } else if (action === 'revoke') {
+ if (!groupId || !link || revoked || !canRevoke) return;
+ const result = await api().revokeInvite({ groupId, link, clientId: revokeOperation.current });
+ if (!current()) return;
+ setRevokeConfirm(false);
+ if (!result.ok) {
+ if (result.errorCode === 'INVITE_REVOKE_UNSUPPORTED') setRevokeUnsupported(true);
+ setError(t(chatErrorKey(result.errorCode))); return;
+ }
+ if (result.revoked !== true) { setError(t(key('requestFailed'))); return; }
+ setRevoked(true); operation.current = crypto.randomUUID();
+ toast.success(t(key('revokedLink')));
+ } else if (groupId) {
const result = await api().createInvite({ groupId, clientId: operation.current });
if (!current()) return;
if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
setLink(result.link);
+ setExpiresAt(result.expiresAt); setReusable(result.reusable); setNow(Date.now());
+ setRevoked(false); setRevokeUnsupported(false); revokeOperation.current = crypto.randomUUID();
} else if (!preview) {
const result = await api().previewInvite({ link });
if (!current()) return;
if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
- setPreview(result);
+ setPreview(result); setNow(Date.now());
} else if (preview.joined) {
onJoined?.(preview.groupId); onClose();
} else {
+ if (expired || (typeof expiry === 'string' && Date.parse(expiry) <= Date.now())) return;
const result = await api().acceptInvite({ link, clientId: operation.current });
if (!current()) return;
- if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
+ if (!result.ok) {
+ if (['INVITATION_NOT_FOUND', 'INVITATION_UNAVAILABLE'].includes(result.errorCode)) setPreview(null);
+ setError(t(chatErrorKey(result.errorCode))); return;
+ }
refreshBotGroups(); onJoined?.(result.groupId); onClose();
}
- } catch { if (current()) setError(t(key('requestFailed'))); }
- finally { busyRef.current = false; if (current()) setBusy(false); }
+ } catch {
+ if (current()) { setRevokeConfirm(false); setError(t(key(action === 'copy' ? 'copyFailed' : 'requestFailed'))); }
+ }
+ finally {
+ busyRef.current = false;
+ // Request results belong to their owner generation; transient UI cleanup
+ // belongs to the mounted dialog, which can survive a same-owner update.
+ if (mounted.current) {
+ setBusy(false);
+ if (action === 'revoke') setRevokeConfirm(false);
+ }
+ }
}
const title = t(key(groupId ? 'invite' : 'join'));
return <Dialog.Root open onOpenChange={open => !busyRef.current && !open && onClose()}>
@@ -57,24 +115,30 @@ export function ChatInviteDialog({ groupId, initialLink = '', onClose, onJoined
className="modal-panel fixed inset-0 z-[71] m-auto flex h-fit max-h-[85vh] w-[min(460px,calc(100vw-32px))] flex-col gap-4 p-5 outline-none">
<Dialog.Title className="text-18 font-medium text-[var(--confirm-title)]">{title}</Dialog.Title>
<Dialog.Description className="text-13 leading-normal text-[var(--confirm-desc)]">{t(key(groupId ? 'inviteDescription' : 'joinDescription'))}</Dialog.Description>
- {(!groupId || link) && <Input aria-label={t(key('inviteLink'))} value={link} readOnly={!!groupId} disabled={busy}
+ {(!groupId || link) && <Input aria-label={t(key('inviteLink'))} value={link} readOnly={!!groupId} disabled={busy || revoked}
placeholder={t(key('pasteLink'))} onChange={value => { setLink(value); setPreview(null); setError(''); operation.current = crypto.randomUUID(); }} />}
{preview && <div className="space-y-1 rounded-lg bg-[var(--surface-elevated)] p-3">
<p className="text-15 font-medium text-[var(--text-primary)]">{preview.name}</p>
<p className="text-13 text-[var(--text-secondary)]">{t(key('invitedBy'), { name: preview.inviterName })}</p>
</div>}
+ {validity && <p role="status" className="text-13 leading-normal text-[var(--text-secondary)]">{validity}</p>}
+ {groupId && link && !revoked && !expired && !canRevoke && <p className="text-13 leading-normal text-[var(--text-secondary)]">{t(key('revokeUnsupported'))}</p>}
{error && <p role="alert" className="text-13 text-[var(--error-fg)]">{error}</p>}
- <div className="flex justify-end gap-2">
+ <div className="flex flex-wrap justify-end gap-2">
<Button variant="secondary" palette="confirmation" size="lg" disabled={busy} onClick={onClose}>{t('bots.close')}</Button>
- {groupId && link
- ? <Button variant="cta" palette="confirmation" size="lg" onClick={() => {
- void navigator.clipboard.writeText(link).then(() => toast.success(t(key('copied')))).catch(() => setError(t(key('copyFailed'))));
- }}>{t(key('copyLink'))}</Button>
- : <Button variant="cta" palette="confirmation" size="lg" loading={busy} disabled={!groupId && !link.trim()} onClick={() => void run()}>
+ {groupId && link && !revoked && !expired && <Button variant="secondary" palette="confirmation" size="lg" disabled={busy || !canRevoke} onClick={() => setRevokeConfirm(true)}>{t(key('revokeLink'))}</Button>}
+ {groupId && link && !expired && !revoked
+ ? <Button variant="cta" palette="confirmation" size="lg" loading={busy} onClick={() => void run('copy')}>{t(key('copyLink'))}</Button>
+ : <Button variant="cta" palette="confirmation" size="lg" loading={busy} disabled={!groupId && (!link.trim() || (expired && !preview?.joined))} onClick={() => void run()}>
{t(key(groupId ? 'createLink' : preview ? (preview.joined ? 'openGroup' : 'accept') : 'previewInvite'))}
</Button>}
</div>
</Dialog.Content>
</Dialog.Portal>
+ <ConfirmDialog open={revokeConfirm} cancelFirst presentation="standard"
+ onOpenChange={open => { if (!busyRef.current) setRevokeConfirm(open); }}
+ title={t(key('revokeLink'))} description={t(key('revokeDescription'))}
+ confirmText={t(key('revokeLink'))} confirmVariant="destructive" loading={busy}
+ onConfirm={() => void run('revoke')} />
</Dialog.Root>;
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatInviteDialog.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatInviteDialog.test.tsx
new file mode 100644
index 0000000000..fff4025a0a
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatInviteDialog.test.tsx
@@ -0,0 +1,184 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { ChatInviteDialog } from '../ChatInviteDialog';
+const mocks = vi.hoisted(() => ({ createInvite: vi.fn(), previewInvite: vi.fn(), acceptInvite: vi.fn(), revokeInvite: vi.fn(), copy: vi.fn(), success: vi.fn() }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, values?: { date?: string }) => values?.date ? `${key}: ${values.date}` : key, i18n: { language: 'en' } }) }));
+vi.mock('../botGroupStore', () => ({ refreshBotGroups: vi.fn() }));
+vi.mock('@/lib/toast', () => ({ toast: { success: mocks.success } }));
+const k = (name: string) => `bots.groupChat.server.${name}`;
+const link = `cindy://chat-invite/${'a'.repeat(43)}`;
+beforeEach(() => {
+ vi.clearAllMocks(); setDataOwnerGeneration('account', 1);
+ mocks.createInvite.mockResolvedValue({ ok: true, link, expiresAt: null, reusable: true });
+ mocks.previewInvite.mockResolvedValue({ ok: true, groupId: 'room', name: 'Room', inviterName: 'Host', expiresAt: null, reusable: true, joined: false });
+ mocks.copy.mockResolvedValue(undefined);
+ mocks.revokeInvite.mockResolvedValue({ ok: true, revoked: true });
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: mocks.copy } });
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: { chatServer: mocks } } });
+});
+afterEach(() => { cleanup(); vi.useRealTimers(); });
+async function create() {
+ render(<ChatInviteDialog groupId="room" onClose={vi.fn()} />);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('createLink') })));
+}
+describe('invitation validity', () => {
+ it('shows null as reusable and copies the same link repeatedly without generating more', async () => {
+ await create();
+ expect(screen.getByRole('status').textContent).toBe(k('reusableLink'));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('copyLink') })));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('copyLink') })));
+ expect(mocks.copy.mock.calls).toEqual([[link], [link]]);
+ expect(mocks.createInvite).toHaveBeenCalledOnce();
+ });
+ it('shows an old server expiry as single use and never calls it permanent', async () => {
+ mocks.createInvite.mockResolvedValue({ ok: true, link, expiresAt: '2099-10-09T12:00:00Z' });
+ await create();
+ expect(screen.getByRole('status').textContent).toContain(k('singleUseUntil'));
+ expect(screen.queryByText(k('reusableLink'))).toBeNull();
+ });
+ it('stops copying when the open dialog reaches its expiry and generates with a fresh id', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
+ vi.setSystemTime(new Date('2026-10-09T12:00:00Z'));
+ mocks.createInvite.mockResolvedValueOnce({ ok: true, link, expiresAt: '2026-10-09T12:00:01Z' });
+ await create();
+ await act(async () => { vi.advanceTimersByTime(1001); });
+ expect(screen.getByRole('status').textContent).toBe(k('expiredLink'));
+ expect(screen.queryByRole('button', { name: k('copyLink') })).toBeNull();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('createLink') })));
+ expect(mocks.createInvite.mock.calls[0][0].clientId).not.toBe(mocks.createInvite.mock.calls[1][0].clientId);
+ });
+ it('disables acceptance for expired previews', async () => {
+ mocks.previewInvite.mockResolvedValue({ ok: true, groupId: 'room', name: 'Room', inviterName: 'Host', expiresAt: '2000-01-01T00:00:00Z', joined: false });
+ render(<ChatInviteDialog initialLink={link} onClose={vi.fn()} />);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('previewInvite') })));
+ expect(screen.getByRole('status').textContent).toBe(k('expiredLink'));
+ expect((screen.getByRole('button', { name: k('accept') }) as HTMLButtonElement).disabled).toBe(true);
+ expect(mocks.acceptInvite).not.toHaveBeenCalled();
+ });
+ it('requires confirmation and cancelling preserves the copyable link', async () => {
+ await create();
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ expect(mocks.revokeInvite).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'commonUi.confirmDialog.cancel' }));
+ expect(mocks.revokeInvite).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: k('copyLink') })).toBeTruthy();
+ });
+ it('revokes only this link, disables it, and generates a new link with a fresh id', async () => {
+ await create();
+ const newLink = `cindy://chat-invite/${'b'.repeat(43)}`;
+ mocks.createInvite.mockResolvedValue({ ok: true, link: newLink, expiresAt: null, reusable: true });
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ await act(async () => fireEvent.click(screen.getAllByRole('button', { name: k('revokeLink') }).at(-1)!));
+ expect(mocks.revokeInvite).toHaveBeenCalledWith({ groupId: 'room', link, clientId: expect.any(String) });
+ expect(screen.getByRole('status').textContent).toBe(k('revokedLink'));
+ expect((screen.getByRole('textbox') as HTMLInputElement).disabled).toBe(true);
+ expect(screen.queryByRole('button', { name: k('copyLink') })).toBeNull();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('createLink') })));
+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(newLink);
+ expect(mocks.createInvite.mock.calls[0][0].clientId).not.toBe(mocks.createInvite.mock.calls[1][0].clientId);
+ expect(screen.getByRole('status').textContent).toBe(k('reusableLink'));
+ });
+ it.each(['ROLE_REQUIRED', 'INVITATION_NOT_FOUND', 'REQUEST_TIMEOUT', 'INVITE_REVOKE_UNSUPPORTED'])('retains state when revoke fails with %s', async errorCode => {
+ mocks.revokeInvite.mockResolvedValue({ ok: false, errorCode });
+ await create();
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ await act(async () => fireEvent.click(screen.getAllByRole('button', { name: k('revokeLink') }).at(-1)!));
+ expect(screen.getByRole('alert')).toBeTruthy();
+ expect(screen.getByRole('status').textContent).toBe(k('reusableLink'));
+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(link);
+ expect(screen.getByRole('button', { name: k('copyLink') })).toBeTruthy();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+ it('disables revoke with an explicit fallback for an old server response', async () => {
+ mocks.createInvite.mockResolvedValue({ ok: true, link, expiresAt: '2099-10-09T12:00:00Z' });
+ await create();
+ expect(screen.getByText(k('revokeUnsupported'))).toBeTruthy();
+ expect((screen.getByRole('button', { name: k('revokeLink') }) as HTMLButtonElement).disabled).toBe(true);
+ expect(mocks.revokeInvite).not.toHaveBeenCalled();
+ });
+ it('keeps the confirmation and blocks copy, dismiss and duplicate revocation while pending', async () => {
+ let finish!: (value: unknown) => void;
+ mocks.revokeInvite.mockReturnValue(new Promise(resolve => { finish = resolve; }));
+ await create();
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ const confirm = screen.getByRole('button', { name: k('revokeLink') });
+ fireEvent.click(confirm); fireEvent.click(confirm);
+ expect(mocks.revokeInvite).toHaveBeenCalledOnce();
+ expect(confirm.hasAttribute('disabled')).toBe(true);
+ expect(screen.getByRole('alertdialog')).toBeTruthy();
+ expect((screen.getByRole('button', { name: 'commonUi.confirmDialog.cancel' }) as HTMLButtonElement).disabled).toBe(true);
+ await act(async () => finish({ ok: true, revoked: true }));
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+ it('reuses the same revocation id after an uncertain timeout', async () => {
+ mocks.revokeInvite.mockResolvedValueOnce({ ok: false, errorCode: 'REQUEST_TIMEOUT' });
+ await create();
+ for (let i = 0; i < 2; i++) {
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('revokeLink') })));
+ }
+ expect(mocks.revokeInvite.mock.calls[0][0]).toEqual(mocks.revokeInvite.mock.calls[1][0]);
+ expect(screen.getByRole('status').textContent).toBe(k('revokedLink'));
+ });
+ it('does not apply a revocation result or toast from an old account', async () => {
+ let finish!: (value: unknown) => void;
+ mocks.revokeInvite.mockReturnValue(new Promise(resolve => { finish = resolve; }));
+ await create();
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ setDataOwnerGeneration('other-account', 2);
+ await act(async () => finish({ ok: true, revoked: true }));
+ expect(screen.queryByText(k('revokedLink'))).toBeNull();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+ it.each(['success', 'error', 'rejection'])('clears a pending revoke after a same-account generation update on %s', async outcome => {
+ let finish!: (value: unknown) => void;
+ let reject!: (reason: Error) => void;
+ mocks.revokeInvite.mockReturnValue(new Promise((resolve, fail) => { finish = resolve; reject = fail; }));
+ const onClose = vi.fn();
+ render(<ChatInviteDialog groupId="room" onClose={onClose} />);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('createLink') })));
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ fireEvent.click(screen.getByRole('button', { name: k('revokeLink') }));
+ expect((screen.getByRole('button', { name: 'commonUi.confirmDialog.cancel' }) as HTMLButtonElement).disabled).toBe(true);
+ setDataOwnerGeneration('account', 2);
+ await act(async () => {
+ if (outcome === 'rejection') reject(new Error('unavailable'));
+ else finish(outcome === 'success' ? { ok: true, revoked: true } : { ok: false, errorCode: 'ROLE_REQUIRED' });
+ });
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.getByRole('status').textContent).toBe(k('reusableLink'));
+ expect(mocks.success).not.toHaveBeenCalled();
+ const close = screen.getByRole('button', { name: 'bots.close' }) as HTMLButtonElement;
+ expect(close.disabled).toBe(false);
+ fireEvent.click(close);
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+ it('discards a stale reusable preview when the server reports an expired or revoked link on acceptance', async () => {
+ mocks.acceptInvite.mockResolvedValue({ ok: false, errorCode: 'INVITATION_NOT_FOUND' });
+ render(<ChatInviteDialog initialLink={link} onClose={vi.fn()} />);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('previewInvite') })));
+ expect(screen.getByRole('status').textContent).toBe(k('reusableLink'));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('accept') })));
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(screen.getByRole('alert').textContent).toBe(k('invalidInvite'));
+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(link);
+ });
+ it('does not show permanent validity when a response omits the reusable flag', async () => {
+ mocks.createInvite.mockResolvedValue({ ok: true, link, expiresAt: null });
+ await create();
+ expect(screen.queryByText(k('reusableLink'))).toBeNull();
+ });
+ it('retains link and shows a failed clipboard action without a success toast', async () => {
+ mocks.copy.mockRejectedValue(new Error('unavailable'));
+ await create();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: k('copyLink') })));
+ expect(screen.getByRole('alert').textContent).toBe(k('copyFailed'));
+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(link);
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/chatError.ts b/apps/desktop/src/renderer/features/bots/chatError.ts
index 8e29a1257f..702836fa53 100644
--- a/apps/desktop/src/renderer/features/bots/chatError.ts
+++ b/apps/desktop/src/renderer/features/bots/chatError.ts
@@ -1,6 +1,7 @@
const key = (name: string) => `bots.groupChat.server.${name}`;
export function chatErrorKey(code: string) {
+ if (code === 'INVITE_REVOKE_UNSUPPORTED') return key('revokeUnsupported');
if (['INVITATION_NOT_FOUND', 'INVITATION_UNAVAILABLE', 'INVALID_INPUT'].includes(code)) return key('invalidInvite');
if (code === 'MENTION_UNAVAILABLE') return 'bots.groupChat.errors.mentionUnavailable';
if (code === 'LAST_OWNER') return key('settings.lastOwner');
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 13cc23b0b9..4c6494087f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8582,7 +8582,14 @@
"reactionCount": "{{emoji}} · {{count}} reactions",
"invite": "Invite to group",
"join": "Join group",
- "inviteDescription": "This single-use link expires in 24 hours. Accepting joins the group and gives access to its chat history.",
+ "inviteDescription": "People who accept the invitation join the group and can read its chat history.",
+ "revokeLink": "Revoke this link",
+ "revokeDescription": "This link will stop accepting new members. Other invitation links and existing members are unaffected.",
+ "revokedLink": "This invitation link has been revoked.",
+ "revokeUnsupported": "This server does not support revoking invitation links.",
+ "reusableLink": "No expiration · Reusable by multiple people",
+ "singleUseUntil": "Single use · Expires {{date}}",
+ "expiredLink": "This invitation link has expired.",
"joinDescription": "Paste an invitation link to preview the group before joining.",
"inviteLink": "Invitation link",
"pasteLink": "Paste invitation link…",
@@ -8593,7 +8600,7 @@
"accept": "Accept and join",
"openGroup": "Open group",
"previewInvite": "Preview invitation",
- "invalidInvite": "This invitation is invalid, used or expired. Request a new link.",
+ "invalidInvite": "This invitation is invalid, used, expired or revoked. Request a new link.",
"notAllowed": "This account does not have permission. Check your account or contact the group owner.",
"loginRequired": "Sign in to your account and try again.",
"requestFailed": "The chat service is unavailable. Please try again shortly.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1fd97194be..73cf09160e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8567,7 +8567,14 @@
"reactionCount": "{{emoji}} · {{count}} 件のリアクション",
"invite": "グループに招待",
"join": "グループに参加",
- "inviteDescription": "リンクは 24 時間有効で、一度だけ使えます。承諾するとメンバーになり、チャット履歴を閲覧できます。",
+ "inviteDescription": "招待を承諾するとメンバーになり、チャット履歴を閲覧できます。",
+ "revokeLink": "このリンクを無効にする",
+ "revokeDescription": "このリンクからはグループに参加できなくなります。他の招待リンクや既存のメンバーには影響しません。",
+ "revokedLink": "この招待リンクは無効化されました。",
+ "revokeUnsupported": "このサーバーでは招待リンクの無効化に対応していません。",
+ "reusableLink": "有効期限なし · 複数の人が繰り返し利用可能",
+ "singleUseUntil": "1 回のみ利用可能 · {{date}} まで有効",
+ "expiredLink": "この招待リンクは期限切れです。",
"joinDescription": "招待リンクを貼り付けて、グループを確認してから参加してください。",
"inviteLink": "招待リンク",
"pasteLink": "招待リンクを貼り付け…",
@@ -8578,7 +8585,7 @@
"accept": "承諾して参加",
"openGroup": "グループを開く",
"previewInvite": "招待を確認",
- "invalidInvite": "招待が無効、使用済み、または期限切れです。新しいリンクを取得してください。",
+ "invalidInvite": "招待が無効、使用済み、期限切れ、または無効化されています。新しいリンクを取得してください。",
"notAllowed": "このアカウントに権限がありません。アカウントを確認するか、グループ管理者に連絡してください。",
"loginRequired": "ログインしてから再試行してください。",
"requestFailed": "チャットサービスに接続できません。しばらくしてから再試行してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 69c9c5e9ee..b7670e7383 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8567,7 +8567,14 @@
"reactionCount": "{{emoji}} · 반응 {{count}}개",
"invite": "그룹에 초대",
"join": "그룹 참여",
- "inviteDescription": "이 링크는 24시간 동안 한 번만 사용할 수 있습니다. 수락하면 그룹 구성원이 되어 대화 기록을 볼 수 있습니다.",
+ "inviteDescription": "초대를 수락하면 그룹 구성원이 되어 대화 기록을 볼 수 있습니다.",
+ "revokeLink": "이 링크 취소",
+ "revokeDescription": "이 링크로는 더 이상 그룹에 참여할 수 없습니다. 다른 초대 링크와 기존 구성원은 영향을 받지 않습니다.",
+ "revokedLink": "이 초대 링크는 취소되었습니다.",
+ "revokeUnsupported": "현재 서버는 초대 링크 취소를 지원하지 않습니다.",
+ "reusableLink": "만료 없음 · 여러 사람이 반복 사용 가능",
+ "singleUseUntil": "한 번만 사용 가능 · {{date}}에 만료",
+ "expiredLink": "이 초대 링크는 만료되었습니다.",
"joinDescription": "초대 링크를 붙여 넣고 그룹을 확인한 후 참여하세요.",
"inviteLink": "초대 링크",
"pasteLink": "초대 링크 붙여 넣기…",
@@ -8578,7 +8585,7 @@
"accept": "수락하고 참여",
"openGroup": "그룹 열기",
"previewInvite": "초대 확인",
- "invalidInvite": "유효하지 않거나 사용 또는 만료된 초대입니다. 새 링크를 받으세요.",
+ "invalidInvite": "유효하지 않거나 사용, 만료 또는 취소된 초대입니다. 새 링크를 받으세요.",
"notAllowed": "현재 계정에 권한이 없습니다. 계정을 확인하거나 그룹 소유자에게 문의하세요.",
"loginRequired": "현재 계정에 로그인한 후 다시 시도하세요.",
"requestFailed": "채팅 서비스에 연결할 수 없습니다. 잠시 후 다시 시도하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 17d7f5699b..50b5257d80 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8567,7 +8567,14 @@
"reactionCount": "{{emoji}} · {{count}} 人回应",
"invite": "邀请加入群聊",
"join": "加入群聊",
- "inviteDescription": "链接 24 小时内有效,只能使用一次。对方接受后会成为群成员,可阅读群聊记录。",
+ "inviteDescription": "对方接受邀请后会成为群成员,可阅读群聊记录。",
+ "revokeLink": "撤销此链接",
+ "revokeDescription": "此链接将无法再用于加入群聊。其他邀请链接和已加入的成员不受影响。",
+ "revokedLink": "此邀请链接已撤销。",
+ "revokeUnsupported": "当前服务不支持撤销邀请链接。",
+ "reusableLink": "长期有效 · 多人可重复使用",
+ "singleUseUntil": "只能使用一次 · {{date}} 到期",
+ "expiredLink": "邀请链接已过期。",
"joinDescription": "粘贴邀请链接,查看群聊后再确认加入。",
"inviteLink": "邀请链接",
"pasteLink": "粘贴邀请链接…",
@@ -8578,7 +8585,7 @@
"accept": "接受并加入",
"openGroup": "打开群聊",
"previewInvite": "查看邀请",
- "invalidInvite": "邀请无效、已使用或已过期,请获取新的邀请链接。",
+ "invalidInvite": "邀请无效、已使用、已过期或已撤销,请获取新的邀请链接。",
"notAllowed": "当前账号没有权限,请检查账号或联系群主。",
"loginRequired": "请先登录当前账号,再重试。",
"requestFailed": "群聊服务暂时无法连接,请稍后重试。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 09c9d219f7..deb338ada6 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8567,7 +8567,14 @@
"reactionCount": "{{emoji}} · {{count}} 人回應",
"invite": "邀請加入群聊",
"join": "加入群聊",
- "inviteDescription": "連結在 24 小時內有效,只能使用一次。對方接受後會成為群組成員,可閱讀群聊記錄。",
+ "inviteDescription": "對方接受邀請後會成為群組成員,可閱讀群聊記錄。",
+ "revokeLink": "撤銷此連結",
+ "revokeDescription": "此連結將無法再用於加入群組。其他邀請連結和已加入的成員不受影響。",
+ "revokedLink": "此邀請連結已撤銷。",
+ "revokeUnsupported": "目前服務不支援撤銷邀請連結。",
+ "reusableLink": "長期有效 · 可供多人重複使用",
+ "singleUseUntil": "只能使用一次 · {{date}} 到期",
+ "expiredLink": "邀請連結已過期。",
"joinDescription": "貼上邀請連結,查看群組後再確認加入。",
"inviteLink": "邀請連結",
"pasteLink": "貼上邀請連結…",
@@ -8578,7 +8585,7 @@
"accept": "接受並加入",
"openGroup": "開啟群組",
"previewInvite": "查看邀請",
- "invalidInvite": "邀請無效、已使用或已過期,請取得新的邀請連結。",
+ "invalidInvite": "邀請無效、已使用、已過期或已撤銷,請取得新的邀請連結。",
"notAllowed": "目前帳號沒有權限,請檢查帳號或聯絡群主。",
"loginRequired": "請先登入目前帳號,再重試。",
"requestFailed": "暫時無法連線至群聊服務,請稍後重試。",
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index 3fcc36c723..fc66e2e957 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -36,11 +36,21 @@ XDT_CDP_PORT=9239 pnpm restart:desktop:remote --region=global -- --isolated=chat
## 操作路径
1. 伙伴侧栏 → 加号 → 新建群聊。可以选择零到六位本机伙伴,建群后再邀请人。
-2. 群顶栏邀请按钮 → 生成邀请链接 → 复制。链接 24 小时有效、一次使用;群主或管理员可以创建。
+2. 群顶栏邀请按钮 → 生成邀请链接 → 复制。群主或管理员可以创建;按服务端响应显示规则:`expiresAt: null` 且 `reusable: true` 才是长期有效、多人重复使用,有到期时间的旧式链接仍按实际日期、单次使用展示。
3. 另一账号:伙伴侧栏标题旁的加入按钮 → 粘贴链接 → 查看邀请 → 接受并加入。预览只展示群名和邀请者,不开放历史;加入后按群的历史策略读取。
4. 每条消息下面可打开回复面板、添加/取消表情回应。消息显示回复数和回应人数,自己的回应有选中状态。伙伴回复 Thread 消息时,结果写回同一 Thread。
5. 两个窗口分别发消息、回复和回应;检查实时刷新、不同作者名字及本人标记。退出其中一个 DEV 后,另一个仍能读取历史;重开 DEV 重新从服务器读取。
+### 邀请有效期与单链接撤销验收
+
+以下检查只在已授权的隔离测试环境或离线 fixture 中执行,不操作真实群或生产链接。新客户端可先发布;长期复用与撤销依赖服务端对应迁移及新版实例全部完成滚动更新,旧实例可能拒绝 `expiresAt: null` 的新链接。
+
+- 新服务端返回 `expiresAt: null, reusable: true`:创建与预览都显示长期可重复使用;反复复制得到同一链接,不额外生成。用多个受邀测试身份接受同一链接,前一次接受不消耗链接;预览仍不开放群历史。
+- 旧服务端省略 `reusable`、返回日期:显示实际到期时间和单次使用,撤销按钮禁用并提示不支持;新服务端返回的存量日期链接也保留到期、单次语义。日期到期后不再复制或接受,不能统一标为长期。
+- 群主或管理员点击当前链接的撤销按钮:确认文字明确只撤销这一条;取消确认不发撤销请求,原链接仍可复制。普通成员或不属于当前群的链接应被服务端拒绝。
+- 确认撤销仅发送当前 token 和操作标识;只有 HTTP 200 且 `revoked: true` 才展示已撤销,禁用旧链接及复制。旧链接的预览或接受应失败,其他链接与已有成员保持有效;再次生成使用新操作标识并得到新的有效链接。
+- 权限、网络或旧路由错误保留链接并显示准确错误,404 不能当作撤销成功;不支持撤销时明确降级。同一次不确定失败的重试沿用操作标识,不以客户端本地状态冒充服务端撤销。
+
## 数据与执行边界
现有群界面 → 受信 IPC → Main `chatServer.ts` → 清单配置的 HTTPS/WSS → PostgreSQL。账号令牌仅由 Main 从正常登录服务读取;不透传给 renderer,不写入测试配置。切换账号会废弃旧请求、连接及执行租约上下文,并重新注册当前账号的伙伴。
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 6b28bbd9c6..7f49959f82 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -370,3 +370,20 @@ Desktop 群聊只对 `TOKEN_EXPIRED`、`INVALID_TOKEN`、`AUTH_REQUIRED` 的 401
本段只描述 Desktop 已有应用协议的消费,不声明存在 HTTPS 落地页或 Mobile 加群入口。
实现见 `main/deepLink.ts`、`renderer/features/bots/ChatInviteHost.tsx`;离线浏览器转交回归见
`chatInviteBrowserHandoff.test.tsx`,原生系统唤起仍需相应平台验收。
+
+### Desktop 群邀请链接的有效期与撤销
+
+邀请弹窗按服务端真实响应显示规则:只有 `expiresAt=null` 且 `reusable=true` 才标为长期有效、
+可供多人重复使用。旧服务端返回的到期时间及省略的 `reusable` 仍按单次链接显示实际到期时间;
+不把缺失字段当作永久链接。到期后停止复制和接受,已加入成员仍可打开群聊。
+
+「撤销此链接」需确认,只作废弹窗中当前这一条链接,不影响同群其他链接或已加入成员。
+主进程重新核对当前账号拥有的已加入群主/管理员 Actor,服务端仍为最终权限权威;撤销 token
+只放在请求正文中。仅 HTTP 200 与 `{revoked:true}` 表示成功,失败保留原链接与错误。
+成功后旧链接不可再复制,生成新链接使用新的操作标识,失败重试保持该操作标识。
+未声明新合同或不支持撤销的服务端禁用撤销入口并提示,不以本地状态模拟撤销。
+
+新客户端可先发布并兼容旧服务端;长期链接与撤销需完成新版服务端及其 nullable migration 的部署。
+旧客户端的邀请弹窗不读取到期字段,因此可消费新响应但不显示准确的新规则,也无撤销入口;
+旧服务端将新版 null 链接视为不可用,服务端滚动期间不能宣称长期链接已完整可用。
+回归见 `chatServerInvitations.test.ts`、`ChatInviteDialog.test.tsx`;本次不新增手机邀请流程。
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 63434ab7d7..917a9d119f 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -434,7 +434,9 @@ export function parseBotGroupPlanRouteKey(routeKey: string | null | undefined):
/** Named, credential-free Desktop chat capabilities. Older/local-only hosts omit them. */
export type ChatServerResult<T> = ({ ok: true } & T) | { ok: false; errorCode: string };
export interface ChatInvitePreview {
- groupId: string; name: string; inviterName: string; expiresAt: string; joined: boolean;
+ groupId: string; name: string; inviterName: string; expiresAt: string | null; joined: boolean;
+ /** Omitted by old servers, whose links remain dated and single-use. */
+ reusable?: boolean;
}
export type ChatGroupAction =
| { type: 'update'; name: string; topic: string; description: string; expectedRevision: number; responseMode?: BotGroupReplyMode; speakingMode?: BotGroupSpeakingMode }
@@ -453,7 +455,8 @@ export interface ChatServerApi {
}>>;
reply(input: { groupId: string; rootId: string; text: string; clientId: string; mentions: BotGroupMention }): Promise<ChatServerResult<{ messageId: string }>>;
react(input: { groupId: string; messageId: string; emoji: string; present: boolean }): Promise<ChatServerResult<Record<never, never>>>;
- createInvite(input: { groupId: string; clientId: string }): Promise<ChatServerResult<{ link: string; expiresAt: string }>>;
+ createInvite(input: { groupId: string; clientId: string }): Promise<ChatServerResult<{ link: string; expiresAt: string | null; reusable?: boolean }>>;
+ revokeInvite(input: { groupId: string; link: string; clientId: string }): Promise<ChatServerResult<{ revoked: true }>>;
previewInvite(input: { link: string }): Promise<ChatServerResult<ChatInvitePreview>>;
acceptInvite(input: { link: string; clientId: string }): Promise<ChatServerResult<{ groupId: string }>>;
}