Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 47 additions & 8 deletions packages/bridge/src/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -2598,6 +2599,7 @@ export class DialogRpc {

async sendMedia(req: SendMediaRequest, excludeConnection?: ServerConnection): Promise<tl.TypeUpdates> {
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)
Expand All @@ -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,
})
Expand All @@ -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,
})
Expand All @@ -2635,6 +2637,7 @@ export class DialogRpc {
async sendMultiMedia(req: SendMultiMediaRequest, excludeConnection?: ServerConnection): Promise<tl.TypeUpdates> {
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)))
Expand All @@ -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
})
}
Expand Down Expand Up @@ -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<void> {
/**
* 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<StoredDraft | undefined> {
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<void> {
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))
}
Expand Down
76 changes: 72 additions & 4 deletions packages/bridge/src/drafts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((resolve) => { releaseSend = resolve })
const sendStarted = new Promise<void>((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(),
)
})
})
Expand Down
Loading