From 5b166910cb5a69fe69c07cbdddd1910b06c9f7bf Mon Sep 17 00:00:00 2001 From: std-external <201375710+std-external@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:37:16 +0800 Subject: [PATCH] =?UTF-8?q?bridge:=20=E5=8F=91=E9=80=81=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E5=90=8E=E5=8F=AA=E6=B8=85=E8=A2=AB=E5=8F=91=E5=87=BA=E7=9A=84?= =?UTF-8?q?=E9=82=A3=E4=BB=BD=E8=8D=89=E7=A8=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 慢网下发完上一条时会把用户正在打的下一条一起清掉:_clearDraftAfterSend 在 发送完成的回调里直接删掉会话当前草稿,还推一条 draftMessageEmpty,客户端把 云端草稿应用到输入框就空了。 发送开始前快照草稿,完成时只有与快照的 date/message 一致才清那一条;发送前 没有草稿或期间又打了新的都不动。任何情况下都不再推 draftMessageEmpty: 发送端自己按下发送时已经清过输入框,事后推空草稿只会盖掉别处正在打的内容。 sendMedia / sendMultiMedia 同一处理。 --- packages/bridge/src/dialogs.ts | 55 +++++++++++++++++---- packages/bridge/src/drafts.test.ts | 76 ++++++++++++++++++++++++++++-- 2 files changed, 119 insertions(+), 12 deletions(-) diff --git a/packages/bridge/src/dialogs.ts b/packages/bridge/src/dialogs.ts index 325826f3..26c8c66b 100644 --- a/packages/bridge/src/dialogs.ts +++ b/packages/bridge/src/dialogs.ts @@ -2485,8 +2485,9 @@ export class DialogRpc { const existing = this._sentByRandomId.get(randomId) if (existing) return existing + const draft = req.clearDraft ? await this._draftBeforeSend(req.peer, req.replyTo) : undefined const pending = this._sendMessage(req, excludeConnection).then(async (result) => { - if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo) + if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo, draft) return result }) this._sentByRandomId.set(randomId, pending) @@ -2598,6 +2599,7 @@ export class DialogRpc { async sendMedia(req: SendMediaRequest, excludeConnection?: ServerConnection): Promise { if (req.scheduleDate !== undefined) throw new RpcError(400, 'SCHEDULED_MESSAGES_UNAVAILABLE') + const draft = req.clearDraft ? await this._draftBeforeSend(req.peer, req.replyTo) : undefined return this._sendMediaOnce(req.randomId.toString(), async () => { const startedAt = performance.now() const resolved = await this._resolveSendMedia(req.media) @@ -2612,7 +2614,7 @@ export class DialogRpc { ) const sendMs = performance.now() - sendAt await this._stickers?.markUsedByRef(resolved.providerId, resolved.stickerId) - if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo) + if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo, draft) this._traceSlowMediaRpc('sendMedia', { resolveMs, sendMs, totalMs: performance.now() - startedAt, }) @@ -2624,7 +2626,7 @@ export class DialogRpc { req.peer, { parts }, [resolved.upload], [req.randomId], req.replyTo, excludeConnection, ) const sendMs = performance.now() - sendAt - if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo) + if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo, draft) this._traceSlowMediaRpc('sendMedia', { resolveMs, sendMs, totalMs: performance.now() - startedAt, }) @@ -2635,6 +2637,7 @@ export class DialogRpc { async sendMultiMedia(req: SendMultiMediaRequest, excludeConnection?: ServerConnection): Promise { if (req.scheduleDate !== undefined) throw new RpcError(400, 'SCHEDULED_MESSAGES_UNAVAILABLE') const randomId = req.multiMedia.map((item) => item.randomId.toString()).join(':') + const draft = req.clearDraft ? await this._draftBeforeSend(req.peer, req.replyTo) : undefined return this._sendMediaOnce(randomId, async () => { if (!req.multiMedia.length) throw new RpcError(400, 'MEDIA_EMPTY') const resolved = await Promise.all(req.multiMedia.map((item) => this._resolveSendMedia(item.media))) @@ -2652,7 +2655,7 @@ export class DialogRpc { req.replyTo, excludeConnection, ) - if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo) + if (req.clearDraft) await this._clearDraftAfterSend(req.peer, req.replyTo, draft) return updates }) } @@ -6186,14 +6189,50 @@ export class DialogRpc { await this._onDraftUpdate(this._session, update, this._authKeyId) } - private async _clearDraftAfterSend(peer: tl.TypeInputPeer, replyTo?: tl.TypeInputReplyTo): Promise { + /** + * The draft a send is about to consume. + * + * The client writes the next draft as soon as the user starts typing, which + * can happen while a slow send is still in flight. The clear that follows the + * send only knows the draft captured here, so anything written afterwards + * survives. + */ + private async _draftBeforeSend( + peer: tl.TypeInputPeer, + replyTo?: tl.TypeInputReplyTo, + ): Promise { if (!this._drafts) return try { + await this._hydratePeers() const scope = await this._resolveDraftScope(peer, replyTo) + return await this._drafts.get(this._session.platformSessionId, scope.conversationId, scope.topMsgId) + } catch (error) { + this._onTrace?.('draft snapshot before send failed: %s', String(error)) + } + } + + /** + * Drops the stored draft the send was based on, and only that one. + * + * The stored draft is compared with the snapshot taken before the send: a + * newer one means the user already started the next message, so it stays. + * Nothing is published either way: the sending client already cleared its + * own composer when the send started, and an empty draft pushed now would + * make it (or the account's other devices) re-apply a cleared draft on top + * of whatever is being typed. + */ + private async _clearDraftAfterSend( + peer: tl.TypeInputPeer, + replyTo: tl.TypeInputReplyTo | undefined, + sentDraft: StoredDraft | undefined, + ): Promise { + if (!this._drafts || !sentDraft) return + try { + const scope = await this._resolveDraftScope(peer, replyTo) + const current = await this._drafts.get(this._session.platformSessionId, scope.conversationId, scope.topMsgId) + if (!current) return + if (current.draft.date !== sentDraft.draft.date || current.draft.message !== sentDraft.draft.message) return await this._drafts.remove(this._session.platformSessionId, scope.conversationId, scope.topMsgId) - await this._publishDraft(scope.conversationId, scope.topMsgId, { - _: 'draftMessageEmpty', date: Math.floor(Date.now() / 1000), - }) } catch (error) { this._onTrace?.('draft clear after send failed: %s', String(error)) } diff --git a/packages/bridge/src/drafts.test.ts b/packages/bridge/src/drafts.test.ts index 9aeed3e7..4e563d58 100644 --- a/packages/bridge/src/drafts.test.ts +++ b/packages/bridge/src/drafts.test.ts @@ -185,19 +185,87 @@ describe('bridge-local drafts', () => { ) await rpc.saveDraft({ _: 'messages.saveDraft', peer, message: 'clear on send' }) + // The send consumes the stored draft, but must not announce an empty one: + // the sending client already cleared its composer, and an empty update + // would re-apply a cleared draft over whatever is being typed next. + const publishedBeforeSend = publish.mock.calls.length await rpc.sendMessage({ _: 'messages.sendMessage', peer, message: 'sent body', randomId: Long.ONE, clearDraft: true, }) expect(sent).toHaveLength(1) expect(await drafts.list(session.platformSessionId)).toEqual([]) - expect(publish).toHaveBeenLastCalledWith( + expect(publish.mock.calls.length).toBe(publishedBeforeSend) + }) + + it('keeps the draft started while the previous send is still in flight', async () => { + const database = await createDatabase() + const store = new MessageStore(database) + const drafts = new DraftStore(database) + let releaseSend: () => void = () => {} + let markSendStarted: () => void = () => {} + const sendGate = new Promise((resolve) => { releaseSend = resolve }) + const sendStarted = new Promise((resolve) => { markSendStarted = resolve }) + const platform: IMPlatform = { + capabilities: { + history: true, + send: { text: true, images: false, files: false, mixed: false, maxTextLength: 4096, maxMedia: 0 }, + conversations: { groups: false, channels: false, subchannels: false }, + }, + async subscribe() { return () => {} }, + async getDialogs() { + return { + dialogs: [{ + conversation: { id: 'alice', kind: 'direct' as const, title: 'Alice' }, + unreadCount: 0, + lastMessage: { + id: 'seed', conversationId: 'alice', senderId: 'alice', timestamp: 1_700_000_000, + content: { parts: [{ type: 'text' as const, text: 'seed' }] }, + }, + }], + } + }, + async getHistory() { return { messages: [] } }, + async getUser(_session, id) { return { id, firstName: id === 'self' ? 'Self' : 'Alice' } }, + async sendMessage(_session, target, content) { + markSendStarted() + await sendGate + return { + id: 'sent-1', conversationId: target.id, senderId: 'self', + timestamp: 1_800_000_010, outgoing: true, + content: { parts: content.parts.flatMap((part) => part.type === 'text' ? [part] : []) }, + } + }, + } + const publish = vi.fn(async () => {}) + const rpc = new DialogRpc(platform, session, store, { + dcId: 1, + authKeyId: 'source-auth-key', + drafts, + onDraftUpdate: publish, + }) + await rpc.getDialogs(getDialogsRequest()) + const peer = inputPeer(rpc.peerTlId('alice')) + + await rpc.saveDraft({ _: 'messages.saveDraft', peer, message: 'first message' }) + const sending = rpc.sendMessage({ + _: 'messages.sendMessage', peer, message: 'first message', randomId: Long.ONE, clearDraft: true, + }) + await sendStarted + // The slow send is still in flight while the user starts writing the next one. + await rpc.saveDraft({ _: 'messages.saveDraft', peer, message: 'second message' }) + releaseSend() + await sending + + await expect(drafts.get(session.platformSessionId, 'alice')).resolves.toMatchObject({ + draft: { message: 'second message' }, + }) + expect(publish).not.toHaveBeenCalledWith( session, expect.objectContaining({ - _: 'updateDraftMessage', - draft: expect.objectContaining({ _: 'draftMessageEmpty' }), + _: 'updateDraftMessage', draft: expect.objectContaining({ _: 'draftMessageEmpty' }), }), - 'source-auth-key', + expect.anything(), ) }) })