From 1e8c2521cecb48f95a21a52da6fdeda0240dec39 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:10 +0900 Subject: [PATCH 01/12] =?UTF-8?q?=EB=B3=B4=EB=82=B4=EA=B8=B0=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C:=20=EC=84=9C=EB=B2=84=20=EB=B0=9C=EC=86=A1=20?= =?UTF-8?q?=EC=A7=80=EC=97=B0=20=ED=81=90=EC=99=80=20=EC=B7=A8=EC=86=8C=20?= =?UTF-8?q?API,=20=ED=81=B4=EB=9D=BC=EC=9D=B4=EC=96=B8=ED=8A=B8=20?= =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EC=8A=A4=EB=82=B5=EB=B0=94=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/core/i18n/language_controller.dart | 14 ++++ .../lib/features/message/compose_page.dart | 38 ++++++++-- .../lib/features/settings/settings_page.dart | 20 +++++ apps/client/lib/services/mail_api_client.dart | 22 +++++- apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 38 +++++++++- apps/server/src/mail/SendQueue.ts | 63 ++++++++++++++++ apps/server/src/server.ts | 11 +++ apps/server/test/sendQueue.test.ts | 75 +++++++++++++++++++ 9 files changed, 270 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/mail/SendQueue.ts create mode 100644 apps/server/test/sendQueue.test.ts diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 443bb5f..764002d 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -204,6 +204,20 @@ class AppStrings { 'password' => _ko ? '비밀번호' : 'Password', _ => mode, }; + String get mailSending => _ko ? '메일을 보내는 중입니다.' : 'Sending mail...'; + String get undoSend => _ko ? '보내기 취소' : 'Undo send'; + String get sendCancelled => + _ko ? '보내기를 취소했습니다.' : 'Sending was cancelled.'; + String get sendAlreadySent => + _ko ? '이미 발송되어 취소할 수 없습니다.' : 'Already sent; it cannot be cancelled.'; + String get sendCancelFailed => + _ko ? '취소하지 못했습니다. 메일이 발송될 수 있습니다.' : 'Could not cancel; the mail may be sent.'; + String get undoSendSetting => _ko ? '보내기 취소 시간' : 'Undo send delay'; + String get undoSendSettingDescription => _ko + ? '보낸 메일을 이 시간 동안 서버가 보관하며 취소할 수 있습니다.' + : 'The server holds sent mail for this long so you can cancel it.'; + String secondsLabel(int seconds) => + seconds == 0 ? (_ko ? '끔' : 'Off') : (_ko ? '$seconds초' : '${seconds}s'); String get pushNotifications => _ko ? '푸시 알림' : 'Push notifications'; String get pushNotificationsDescription => _ko ? '새 IMAP 메일은 서버 푸시를 통해 즉시 전달됩니다.' diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index c0f8a58..318dc58 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -134,12 +134,38 @@ class _ComposePageState extends ConsumerState { final accountId = _accountId; if (accountId == null) return; - await ref.read(mailApiClientProvider).sendMail( - accountId: accountId, - to: _toController.text.split(',').map((item) => item.trim()).toList(), - subject: _subjectController.text, - body: _bodyController.text, - ); + final client = ref.read(mailApiClientProvider); + final strings = ref.read(appStringsProvider); + final delay = ref.read(undoSendDelayProvider); + final messenger = ScaffoldMessenger.of(context); + final id = await client.sendMail( + accountId: accountId, + to: _toController.text.split(',').map((item) => item.trim()).toList(), + subject: _subjectController.text, + body: _bodyController.text, + delaySeconds: delay, + ); + + if (delay > 0) { + messenger.showSnackBar(SnackBar( + content: Text(strings.mailSending), + duration: Duration(seconds: delay), + action: SnackBarAction( + label: strings.undoSend, + onPressed: () async { + String result; + try { + result = await client.cancelSend(id) + ? strings.sendCancelled + : strings.sendAlreadySent; + } catch (_) { + result = strings.sendCancelFailed; + } + messenger.showSnackBar(SnackBar(content: Text(result))); + }, + ), + )); + } if (mounted) context.go('/accounts/$accountId/mail'); } diff --git a/apps/client/lib/features/settings/settings_page.dart b/apps/client/lib/features/settings/settings_page.dart index 2fe1823..f048a3d 100644 --- a/apps/client/lib/features/settings/settings_page.dart +++ b/apps/client/lib/features/settings/settings_page.dart @@ -46,6 +46,26 @@ class SettingsPage extends ConsumerWidget { }, ), ), + ListTile( + leading: const Icon(Icons.undo), + title: Text(strings.undoSendSetting), + subtitle: Text(strings.undoSendSettingDescription), + trailing: DropdownButton( + value: ref.watch(undoSendDelayProvider), + items: [ + for (final seconds in undoSendDelayOptions) + DropdownMenuItem( + value: seconds, + child: Text(strings.secondsLabel(seconds)), + ), + ], + onChanged: (value) { + if (value != null) { + ref.read(undoSendDelayProvider.notifier).state = value; + } + }, + ), + ), SwitchListTile( value: true, onChanged: (_) {}, diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..05301f5 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -2,6 +2,11 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +const undoSendDelayOptions = [0, 5, 10, 20, 30]; + +/// Seconds the server holds a sent mail so it can still be cancelled. +final undoSendDelayProvider = StateProvider((ref) => 5); + final mailApiClientProvider = Provider((ref) { return MailApiClient( baseUrl: resolveMailApiBaseUrl(), @@ -190,18 +195,31 @@ class MailApiClient { }); } - Future sendMail({ + /// Queues the mail on the server and returns the id used to cancel it. + Future sendMail({ required String accountId, required List to, required String subject, required String body, + int delaySeconds = 5, }) async { - await _dio.post('/mail/send', data: { + final response = await _dio.post('/mail/send', data: { 'accountId': accountId, 'to': to, 'subject': subject, 'text': body, + 'delaySeconds': delaySeconds, }); + return (response.data as Map)['id'] as String; + } + + /// Returns false when the mail was already sent. + Future cancelSend(String id) async { + final response = await _dio.post( + '/mail/send/$id/cancel', + options: Options(validateStatus: (code) => code == 200 || code == 409), + ); + return response.statusCode == 200; } } diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..3f1b99f 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/sendQueue.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 6e2ebd1..d5005aa 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -2,6 +2,11 @@ import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { MailSender } from "../mail/MailSender.js"; +import { + SendQueue, + defaultUndoDelaySeconds, + undoDelaySeconds +} from "../mail/SendQueue.js"; import type { AuthMode, IncomingMessageContent, @@ -25,7 +30,13 @@ const sendSchema = z.object({ bcc: z.array(z.string().email()).optional(), subject: z.string().default(""), html: z.string().optional(), - text: z.string().optional() + text: z.string().optional(), + delaySeconds: z + .number() + .refine((value) => (undoDelaySeconds as readonly number[]).includes(value), { + message: `delaySeconds must be one of ${undoDelaySeconds.join(", ")}` + }) + .default(defaultUndoDelaySeconds) }); const pushTokenSchema = z.object({ @@ -77,6 +88,7 @@ export async function registerRoutes( app: FastifyInstance, deps: { sender: MailSender; + sendQueue?: SendQueue; accounts: AccountRepository; validateAccount: (account: MailAccount) => Promise; fetchMessageContent: ( @@ -88,6 +100,10 @@ export async function registerRoutes( stopAccountSync: (accountId: string) => Promise; } ): Promise { + const sendQueue = + deps.sendQueue ?? + new SendQueue(deps.sender, (error) => app.log.error({ err: error }, "mail send failed")); + app.get("/health", async () => ({ ok: true })); app.get("/providers", async () => { @@ -339,15 +355,29 @@ export async function registerRoutes( }); app.post("/mail/send", async (request, reply) => { - const draft = sendSchema.parse(request.body) as OutgoingMessageDraft; + const { delaySeconds, ...parsed } = sendSchema.parse(request.body); + const draft = parsed as OutgoingMessageDraft; const account = await deps.accounts.getAccount(draft.accountId); if (!account) { return reply.code(404).send({ error: "Account not found" }); } - const result = await deps.sender.send(account, draft); - return reply.code(202).send(result); + const id = sendQueue.enqueue(account, draft, delaySeconds); + return reply.code(202).send({ id, delaySeconds }); + }); + + app.post("/mail/send/:id/cancel", async (request, reply) => { + const { id } = request.params as { id: string }; + const status = sendQueue.cancel(id); + + if (!status) { + return reply.code(404).send({ error: "Send request not found" }); + } + if (status !== "cancelled") { + return reply.code(409).send({ error: "Message already sent", status }); + } + return reply.code(200).send({ id, status }); }); app.post("/devices/push-token", async (request, reply) => { diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts new file mode 100644 index 0000000..dc23c73 --- /dev/null +++ b/apps/server/src/mail/SendQueue.ts @@ -0,0 +1,63 @@ +import { randomUUID } from "node:crypto"; +import type { MailAccount, OutgoingMessageDraft } from "../domain/types.js"; +import type { MailSender } from "./MailSender.js"; + +export const undoDelaySeconds = [0, 5, 10, 20, 30] as const; +export const defaultUndoDelaySeconds = 5; + +export type SendStatus = "pending" | "sent" | "failed" | "cancelled"; + +interface Entry { + status: SendStatus; + timer?: NodeJS.Timeout; + run: () => Promise; +} + +// shortcut: queue lives in memory; pending mail is flushed on shutdown, but a crash loses it. Persist with scheduled send (issue #34 stage 2). +export class SendQueue { + private readonly entries = new Map(); + + constructor( + private readonly sender: MailSender, + private readonly onError: (error: unknown) => void = () => undefined, + private readonly retainMs = 60_000 + ) {} + + enqueue(account: MailAccount, draft: OutgoingMessageDraft, delaySeconds: number): string { + const id = randomUUID(); + const entry: Entry = { + status: "pending", + run: async () => { + if (entry.status !== "pending") return; + clearTimeout(entry.timer); + entry.status = "sent"; + try { + await this.sender.send(account, draft); + } catch (error) { + entry.status = "failed"; + this.onError(error); + } + setTimeout(() => this.entries.delete(id), this.retainMs).unref(); + } + }; + entry.timer = setTimeout(() => void entry.run(), delaySeconds * 1000); + this.entries.set(id, entry); + return id; + } + + /** Returns undefined for unknown id, otherwise the status after the attempt. */ + cancel(id: string): SendStatus | undefined { + const entry = this.entries.get(id); + if (!entry) return undefined; + if (entry.status === "pending") { + clearTimeout(entry.timer); + entry.status = "cancelled"; + } + return entry.status; + } + + /** Send everything still waiting (server shutdown). */ + async flush(): Promise { + await Promise.all([...this.entries.values()].map((entry) => entry.run())); + } +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47ce656..8900c42 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -15,6 +15,7 @@ import { InMemoryAccountRepository } from "./workers/AccountRepository.js"; import type { AccountRepository } from "./workers/AccountRepository.js"; import { LocalFileAccountRepository } from "./workers/LocalFileAccountRepository.js"; import { MailSyncWorker } from "./workers/MailSyncWorker.js"; +import { SendQueue } from "./mail/SendQueue.js"; import { registerRoutes } from "./api/routes.js"; import { OAuthAccountFlow } from "./auth/OAuthAccountFlow.js"; import { OAuthTokenManager } from "./auth/OAuthTokenManager.js"; @@ -49,8 +50,14 @@ const worker = new MailSyncWorker(accounts, imap, pop3, push, { imapReconnectMaxDelayMs: 60_000 }); +const sendQueue = new SendQueue(sender, (error) => + app.log.error({ err: error }, "mail send failed") +); +app.addHook("onClose", async () => sendQueue.flush()); + await registerRoutes(app, { sender, + sendQueue, accounts, validateAccount: async (account) => { if (account.incomingProtocol === "imap") { @@ -120,6 +127,10 @@ await app.listen({ host: env.HOST }); +for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.once(signal, () => void app.close().finally(() => process.exit(0))); +} + function createPushNotifier(): PushNotifier { if (env.PUSH_PROVIDER !== "apns") return new NoopPushNotifier(); if (!env.APNS_KEY_PATH || !env.APNS_KEY_ID || !env.APNS_TEAM_ID) { diff --git a/apps/server/test/sendQueue.test.ts b/apps/server/test/sendQueue.test.ts new file mode 100644 index 0000000..330cd3f --- /dev/null +++ b/apps/server/test/sendQueue.test.ts @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import type { MailAccount } from "../src/domain/types.js"; +import { registerRoutes } from "../src/api/routes.js"; +import { SendQueue } from "../src/mail/SendQueue.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +async function setup() { + const now = new Date(); + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount({ + id: "account-1", + userId: "demo-user", + providerId: "naver", + emailAddress: "user@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "app-password", + syncStatus: "idle", + createdAt: now, + updatedAt: now + } as MailAccount); + const sent: string[] = []; + const sender = { + send: async (_a: MailAccount, draft: { subject: string }) => { + sent.push(draft.subject); + return { accepted: [], rejected: [] }; + } + }; + const errors: unknown[] = []; + const sendQueue = new SendQueue(sender as never, (e) => errors.push(e)); + const app = Fastify(); + await registerRoutes(app, { accounts, sender: sender as never, sendQueue } as never); + const post = (delaySeconds: number) => + app.inject({ + method: "POST", + url: "/mail/send", + payload: { accountId: "account-1", to: ["a@example.com"], subject: "hi", delaySeconds } + }); + return { app, sent, errors, sendQueue, post }; +} + +test("cancel before delay prevents sending", async () => { + const { app, sent, post } = await setup(); + const { id } = (await post(30)).json(); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 200); + await new Promise((r) => setTimeout(r, 20)); + assert.deepEqual(sent, []); +}); + +test("delay 0 sends, later cancel returns 409", async () => { + const { app, sent, post } = await setup(); + const { id } = (await post(0)).json(); + await new Promise((r) => setTimeout(r, 30)); + assert.deepEqual(sent, ["hi"]); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 409); +}); + +test("unknown id 404 and invalid delay rejected", async () => { + const { app, post } = await setup(); + const cancel = await app.inject({ method: "POST", url: "/mail/send/nope/cancel" }); + assert.equal(cancel.statusCode, 404); + assert.notEqual((await post(7)).statusCode, 202); +}); + +test("flush sends pending mail once and reports failures", async () => { + const { sent, sendQueue, post } = await setup(); + await post(30); + await sendQueue.flush(); + await sendQueue.flush(); + assert.deepEqual(sent, ["hi"]); +}); From 1eae0bf51d4628b76487b5ba5e091e844d20c916 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:51:52 +0900 Subject: [PATCH 02/12] =?UTF-8?q?=EB=B3=B4=EB=82=B4=EA=B8=B0=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C:=20=EC=A2=85=EB=A3=8C=20=EC=8B=9C=20=EC=A7=84?= =?UTF-8?q?=ED=96=89=20=EC=A4=91=20=EB=B0=9C=EC=86=A1=20=EB=8C=80=EA=B8=B0?= =?UTF-8?q?,=20=EC=B7=A8=EC=86=8C=20=ED=95=AD=EB=AA=A9=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC,=20=EC=B7=A8=EC=86=8C=20=EC=8A=A4=EB=82=B5=EB=B0=94?= =?UTF-8?q?=20=EC=A6=89=EC=8B=9C=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - flush가 진행 중인 발송 promise를 기다리고 중복 발송하지 않음 - 취소된 큐 항목도 보존 기간 후 제거 - 취소 스낵바를 대기 중인 스낵바 뒤로 밀리지 않게 즉시 표시하고 실제 발송 시점까지만 노출 --- .../lib/features/message/compose_page.dart | 9 ++++-- apps/server/src/mail/SendQueue.ts | 29 +++++++++++++------ apps/server/test/sendQueue.test.ts | 25 ++++++++++++++++ 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 318dc58..df5028f 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -138,6 +138,7 @@ class _ComposePageState extends ConsumerState { final strings = ref.read(appStringsProvider); final delay = ref.read(undoSendDelayProvider); final messenger = ScaffoldMessenger.of(context); + final started = DateTime.now(); final id = await client.sendMail( accountId: accountId, to: _toController.text.split(',').map((item) => item.trim()).toList(), @@ -146,10 +147,14 @@ class _ComposePageState extends ConsumerState { delaySeconds: delay, ); - if (delay > 0) { + // Server countdown starts at enqueue: show immediately (not behind older snackbars) + // and expire against the real send deadline. + final remaining = Duration(seconds: delay) - DateTime.now().difference(started); + if (delay > 0 && remaining > Duration.zero) { + messenger.clearSnackBars(); messenger.showSnackBar(SnackBar( content: Text(strings.mailSending), - duration: Duration(seconds: delay), + duration: remaining, action: SnackBarAction( label: strings.undoSend, onPressed: () async { diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts index dc23c73..6d4ab3f 100644 --- a/apps/server/src/mail/SendQueue.ts +++ b/apps/server/src/mail/SendQueue.ts @@ -10,6 +10,7 @@ export type SendStatus = "pending" | "sent" | "failed" | "cancelled"; interface Entry { status: SendStatus; timer?: NodeJS.Timeout; + sending?: Promise; run: () => Promise; } @@ -27,17 +28,22 @@ export class SendQueue { const id = randomUUID(); const entry: Entry = { status: "pending", - run: async () => { - if (entry.status !== "pending") return; + run: () => { + // flush() during an in-flight send must await the same promise, never send twice. + if (entry.sending) return entry.sending; + if (entry.status !== "pending") return Promise.resolve(); clearTimeout(entry.timer); entry.status = "sent"; - try { - await this.sender.send(account, draft); - } catch (error) { - entry.status = "failed"; - this.onError(error); - } - setTimeout(() => this.entries.delete(id), this.retainMs).unref(); + entry.sending = (async () => { + try { + await this.sender.send(account, draft); + } catch (error) { + entry.status = "failed"; + this.onError(error); + } + this.expire(id); + })(); + return entry.sending; } }; entry.timer = setTimeout(() => void entry.run(), delaySeconds * 1000); @@ -45,6 +51,10 @@ export class SendQueue { return id; } + private expire(id: string): void { + setTimeout(() => this.entries.delete(id), this.retainMs).unref(); + } + /** Returns undefined for unknown id, otherwise the status after the attempt. */ cancel(id: string): SendStatus | undefined { const entry = this.entries.get(id); @@ -52,6 +62,7 @@ export class SendQueue { if (entry.status === "pending") { clearTimeout(entry.timer); entry.status = "cancelled"; + this.expire(id); } return entry.status; } diff --git a/apps/server/test/sendQueue.test.ts b/apps/server/test/sendQueue.test.ts index 330cd3f..75b6198 100644 --- a/apps/server/test/sendQueue.test.ts +++ b/apps/server/test/sendQueue.test.ts @@ -73,3 +73,28 @@ test("flush sends pending mail once and reports failures", async () => { await sendQueue.flush(); assert.deepEqual(sent, ["hi"]); }); + +test("flush awaits an in-flight send without sending twice", async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const sent: string[] = []; + const sender = { send: async (_a: unknown, d: { subject: string }) => { sent.push(d.subject); await gate; } }; + const queue = new SendQueue(sender as never); + queue.enqueue({} as MailAccount, { subject: "x" } as never, 0); + await new Promise((r) => setTimeout(r, 10)); + let flushed = false; + const flushing = queue.flush().then(() => (flushed = true)); + await new Promise((r) => setTimeout(r, 10)); + assert.equal(flushed, false); + release(); + await flushing; + assert.deepEqual(sent, ["x"]); +}); + +test("cancelled entries are removed after retention", async () => { + const queue = new SendQueue({ send: async () => undefined } as never, undefined, 10); + const id = queue.enqueue({} as MailAccount, {} as never, 30); + assert.equal(queue.cancel(id), "cancelled"); + await new Promise((r) => setTimeout(r, 40)); + assert.equal(queue.cancel(id), undefined); +}); From dbab32fd6600407ea5ad9c9d799104109d37ba6b Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:59:48 +0900 Subject: [PATCH 03/12] =?UTF-8?q?=EB=B0=9C=EC=86=A1=20=ED=81=90=20?= =?UTF-8?q?=EC=9A=A9=EB=9F=89=C2=B7=EB=8F=99=EC=8B=9C=EC=84=B1=20=EC=A0=9C?= =?UTF-8?q?=ED=95=9C:=20=EC=A0=84=EC=B2=B4=20200=C2=B7=EA=B3=84=EC=A0=95?= =?UTF-8?q?=EB=B3=84=2020=20=EC=B4=88=EA=B3=BC=20=EC=8B=9C=20429,=20SMTP?= =?UTF-8?q?=20=EB=8F=99=EC=8B=9C=204=EA=B1=B4,=20=EB=B0=9C=EC=86=A1=20?= =?UTF-8?q?=EB=B3=B8=EB=AC=B8=2010MiB=20=EC=A0=9C=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/server/src/api/routes.ts | 14 ++++++- apps/server/src/mail/SendQueue.ts | 59 +++++++++++++++++++++++++++++- apps/server/test/sendQueue.test.ts | 39 ++++++++++++++++++++ 3 files changed, 108 insertions(+), 4 deletions(-) diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index d5005aa..efa76a2 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -4,6 +4,7 @@ import { z } from "zod"; import type { MailSender } from "../mail/MailSender.js"; import { SendQueue, + SendQueueFullError, defaultUndoDelaySeconds, undoDelaySeconds } from "../mail/SendQueue.js"; @@ -354,7 +355,8 @@ export async function registerRoutes( }; }); - app.post("/mail/send", async (request, reply) => { + // 10 MiB: explicit cap on the send body (Fastify default is 1 MiB). + app.post("/mail/send", { bodyLimit: 10 * 1024 * 1024 }, async (request, reply) => { const { delaySeconds, ...parsed } = sendSchema.parse(request.body); const draft = parsed as OutgoingMessageDraft; const account = await deps.accounts.getAccount(draft.accountId); @@ -363,7 +365,15 @@ export async function registerRoutes( return reply.code(404).send({ error: "Account not found" }); } - const id = sendQueue.enqueue(account, draft, delaySeconds); + let id: string; + try { + id = sendQueue.enqueue(account, draft, delaySeconds); + } catch (error) { + if (error instanceof SendQueueFullError) { + return reply.code(429).send({ error: "Too many pending sends" }); + } + throw error; + } return reply.code(202).send({ id, delaySeconds }); }); diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts index 6d4ab3f..4e13924 100644 --- a/apps/server/src/mail/SendQueue.ts +++ b/apps/server/src/mail/SendQueue.ts @@ -7,7 +7,27 @@ export const defaultUndoDelaySeconds = 5; export type SendStatus = "pending" | "sent" | "failed" | "cancelled"; +export interface SendQueueLimits { + maxEntries: number; + maxPendingPerAccount: number; + maxConcurrentSends: number; +} + +export const defaultSendQueueLimits: SendQueueLimits = { + maxEntries: 200, + maxPendingPerAccount: 20, + maxConcurrentSends: 4 +}; + +export class SendQueueFullError extends Error { + constructor() { + super("Send queue is full"); + } +} + interface Entry { + accountId: string; + settled: boolean; status: SendStatus; timer?: NodeJS.Timeout; sending?: Promise; @@ -17,16 +37,46 @@ interface Entry { // shortcut: queue lives in memory; pending mail is flushed on shutdown, but a crash loses it. Persist with scheduled send (issue #34 stage 2). export class SendQueue { private readonly entries = new Map(); + private readonly limits: SendQueueLimits; + private activeSends = 0; + private readonly waiters: Array<() => void> = []; constructor( private readonly sender: MailSender, private readonly onError: (error: unknown) => void = () => undefined, - private readonly retainMs = 60_000 - ) {} + private readonly retainMs = 60_000, + limits: Partial = {} + ) { + this.limits = { ...defaultSendQueueLimits, ...limits }; + } + + private async acquire(): Promise { + if (this.activeSends < this.limits.maxConcurrentSends) { + this.activeSends++; + return; + } + // The releasing send hands its slot over, so activeSends stays unchanged. + await new Promise((resolve) => this.waiters.push(resolve)); + } + + private release(): void { + const next = this.waiters.shift(); + if (next) next(); + else this.activeSends--; + } enqueue(account: MailAccount, draft: OutgoingMessageDraft, delaySeconds: number): string { + if (this.entries.size >= this.limits.maxEntries) throw new SendQueueFullError(); + let pendingForAccount = 0; + for (const e of this.entries.values()) { + if (e.accountId === account.id && !e.settled) pendingForAccount++; + } + if (pendingForAccount >= this.limits.maxPendingPerAccount) throw new SendQueueFullError(); + const id = randomUUID(); const entry: Entry = { + accountId: account.id, + settled: false, status: "pending", run: () => { // flush() during an in-flight send must await the same promise, never send twice. @@ -35,12 +85,16 @@ export class SendQueue { clearTimeout(entry.timer); entry.status = "sent"; entry.sending = (async () => { + await this.acquire(); try { await this.sender.send(account, draft); } catch (error) { entry.status = "failed"; this.onError(error); + } finally { + this.release(); } + entry.settled = true; this.expire(id); })(); return entry.sending; @@ -62,6 +116,7 @@ export class SendQueue { if (entry.status === "pending") { clearTimeout(entry.timer); entry.status = "cancelled"; + entry.settled = true; this.expire(id); } return entry.status; diff --git a/apps/server/test/sendQueue.test.ts b/apps/server/test/sendQueue.test.ts index 75b6198..911caf2 100644 --- a/apps/server/test/sendQueue.test.ts +++ b/apps/server/test/sendQueue.test.ts @@ -98,3 +98,42 @@ test("cancelled entries are removed after retention", async () => { await new Promise((r) => setTimeout(r, 40)); assert.equal(queue.cancel(id), undefined); }); + +test("enqueue over per-account or total limit is rejected with 429", async () => { + const sender = { send: async () => undefined }; + const queue = new SendQueue(sender as never, undefined, 60_000, { maxPendingPerAccount: 2, maxEntries: 3 }); + const app = Fastify(); + const accounts = new InMemoryAccountRepository(); + const now = new Date(); + for (const id of ["a", "b"]) { + await accounts.addAccount({ id, userId: "u", providerId: "naver", emailAddress: `${id}@example.com`, + authMode: "app-password", incomingProtocol: "imap", encryptedSecretRef: "x", syncStatus: "idle", + createdAt: now, updatedAt: now } as MailAccount); + } + await registerRoutes(app, { accounts, sender: sender as never, sendQueue: queue } as never); + const post = (accountId: string) => + app.inject({ method: "POST", url: "/mail/send", payload: { accountId, to: ["x@example.com"], subject: "s", delaySeconds: 30 } }); + assert.equal((await post("a")).statusCode, 202); + assert.equal((await post("a")).statusCode, 202); + assert.equal((await post("a")).statusCode, 429); + assert.equal((await post("b")).statusCode, 202); + assert.equal((await post("b")).statusCode, 429); + await queue.flush(); +}); + +test("concurrent SMTP sends are capped and waiting entries still go out", async () => { + let running = 0; + let peak = 0; + const sender = { + send: async () => { + peak = Math.max(peak, ++running); + await new Promise((r) => setTimeout(r, 20)); + running--; + } + }; + const queue = new SendQueue(sender as never, undefined, 60_000, { maxConcurrentSends: 2 }); + for (let i = 0; i < 5; i++) queue.enqueue({ id: "a" } as MailAccount, {} as never, 0); + await queue.flush(); + assert.equal(peak, 2); + assert.equal(running, 0); +}); From 59ae6dbba633df1be88aea1ff59facdc97799fa2 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:04:45 +0900 Subject: [PATCH 04/12] =?UTF-8?q?=EB=B3=B4=EB=82=B4=EA=B8=B0=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C:=20=EB=B9=84=EB=8F=99=EA=B8=B0=20=EB=B0=9C=EC=86=A1?= =?UTF-8?q?=20=EC=8B=A4=ED=8C=A8=20=EC=A1=B0=ED=9A=8C(GET=20/mail/send/:id?= =?UTF-8?q?)=EC=99=80=20=EB=8B=A4=EC=8B=9C=20=EC=9E=91=EC=84=B1,=20?= =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EB=82=A8=EC=9D=80=20=EC=8B=9C=EA=B0=84?= =?UTF-8?q?=EC=9D=84=20=EC=84=9C=EB=B2=84=20sendAt=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EA=B3=84=EC=82=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/client/lib/core/app_router.dart | 2 + .../lib/core/i18n/language_controller.dart | 5 ++ .../lib/features/message/compose_page.dart | 77 ++++++++++++++++--- apps/client/lib/services/mail_api_client.dart | 60 +++++++++++++-- apps/client/test/send_failure_test.dart | 59 ++++++++++++++ apps/server/src/api/routes.ts | 15 +++- apps/server/src/mail/SendQueue.ts | 39 +++++++++- apps/server/test/sendQueue.test.ts | 54 ++++++++++++- 8 files changed, 287 insertions(+), 24 deletions(-) create mode 100644 apps/client/test/send_failure_test.dart diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index 7851c6a..bba2bb7 100644 --- a/apps/client/lib/core/app_router.dart +++ b/apps/client/lib/core/app_router.dart @@ -7,6 +7,7 @@ import '../features/accounts/accounts_page.dart'; import '../features/message/compose_page.dart'; import '../features/message/message_page.dart'; import '../features/settings/settings_page.dart'; +import '../services/mail_api_client.dart'; final appRouterProvider = Provider((ref) { return GoRouter( @@ -49,6 +50,7 @@ final appRouterProvider = Provider((ref) { state: state, child: ComposePage( initialAccountId: state.pathParameters['accountId'], + initialDraft: state.extra as ComposeDraft?, ), ), ), diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 764002d..067e12a 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -212,6 +212,11 @@ class AppStrings { _ko ? '이미 발송되어 취소할 수 없습니다.' : 'Already sent; it cannot be cancelled.'; String get sendCancelFailed => _ko ? '취소하지 못했습니다. 메일이 발송될 수 있습니다.' : 'Could not cancel; the mail may be sent.'; + String sendDeliveryFailed(String reason) => _ko + ? '메일을 보내지 못했습니다: $reason' + : 'The mail could not be delivered: $reason'; + String get sendFailedShort => _ko ? '발송에 실패했습니다.' : 'Sending failed.'; + String get rewriteMail => _ko ? '다시 작성' : 'Rewrite'; String get undoSendSetting => _ko ? '보내기 취소 시간' : 'Undo send delay'; String get undoSendSettingDescription => _ko ? '보낸 메일을 이 시간 동안 서버가 보관하며 취소할 수 있습니다.' diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index df5028f..f49a94a 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -14,9 +16,11 @@ class ComposePage extends ConsumerStatefulWidget { const ComposePage({ super.key, this.initialAccountId, + this.initialDraft, }); final String? initialAccountId; + final ComposeDraft? initialDraft; @override ConsumerState createState() => _ComposePageState(); @@ -32,6 +36,12 @@ class _ComposePageState extends ConsumerState { void initState() { super.initState(); _accountId = widget.initialAccountId; + final draft = widget.initialDraft; + if (draft != null) { + _toController.text = draft.to; + _subjectController.text = draft.subject; + _bodyController.text = draft.body; + } } @override @@ -138,8 +148,8 @@ class _ComposePageState extends ConsumerState { final strings = ref.read(appStringsProvider); final delay = ref.read(undoSendDelayProvider); final messenger = ScaffoldMessenger.of(context); - final started = DateTime.now(); - final id = await client.sendMail( + final router = GoRouter.of(context); + final receipt = await client.sendMail( accountId: accountId, to: _toController.text.split(',').map((item) => item.trim()).toList(), subject: _subjectController.text, @@ -147,22 +157,24 @@ class _ComposePageState extends ConsumerState { delaySeconds: delay, ); - // Server countdown starts at enqueue: show immediately (not behind older snackbars) - // and expire against the real send deadline. - final remaining = Duration(seconds: delay) - DateTime.now().difference(started); - if (delay > 0 && remaining > Duration.zero) { + // The countdown comes from the server's deadline: show immediately (not behind + // older snackbars) and expire when the server actually sends. + if (delay > 0 && receipt.remaining > Duration.zero) { messenger.clearSnackBars(); messenger.showSnackBar(SnackBar( content: Text(strings.mailSending), - duration: remaining, + duration: receipt.remaining, action: SnackBarAction( label: strings.undoSend, onPressed: () async { String result; try { - result = await client.cancelSend(id) - ? strings.sendCancelled - : strings.sendAlreadySent; + final status = await client.cancelSend(receipt.id); + result = switch (status) { + 'cancelled' => strings.sendCancelled, + 'failed' => strings.sendFailedShort, + _ => strings.sendAlreadySent, + }; } catch (_) { result = strings.sendCancelFailed; } @@ -172,6 +184,51 @@ class _ComposePageState extends ConsumerState { )); } + // Detached from this page on purpose: the composer closes right after sending. + unawaited(_reportFailure(client, receipt, strings, messenger, router)); + if (mounted) context.go('/accounts/$accountId/mail'); } } + +/// Polls the queued send after the undo window; on failure offers to reopen the draft. +Future _reportFailure( + MailApiClient client, + SendReceipt receipt, + AppStrings strings, + ScaffoldMessengerState messenger, + GoRouter router, +) async { + final outcome = await awaitSendOutcome(client, receipt); + final draft = outcome?.draft; + if (outcome == null || draft == null) return; + messenger.showSnackBar(SnackBar( + content: Text(strings.sendDeliveryFailed(outcome.error ?? '')), + duration: const Duration(seconds: 15), + action: SnackBarAction( + label: strings.rewriteMail, + onPressed: () => router.go('/accounts/${draft.accountId}/compose', extra: draft), + ), + )); +} + +/// Waits out the undo window, then polls a few times. Returns the outcome only when the send failed. +Future awaitSendOutcome( + MailApiClient client, + SendReceipt receipt, { + Duration interval = const Duration(seconds: 2), + int attempts = 10, +}) async { + if (receipt.remaining > Duration.zero) await Future.delayed(receipt.remaining); + for (var i = 0; i < attempts; i++) { + await Future.delayed(interval); + try { + final outcome = await client.fetchSendOutcome(receipt.id); + if (outcome.status == 'failed') return outcome; + if (outcome.status == 'sent' || outcome.status == 'cancelled') return null; + } catch (_) { + // Transient error or expired entry: try again, then give up quietly. + } + } + return null; +} diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 05301f5..323b1eb 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -7,6 +7,32 @@ const undoSendDelayOptions = [0, 5, 10, 20, 30]; /// Seconds the server holds a sent mail so it can still be cancelled. final undoSendDelayProvider = StateProvider((ref) => 5); +class SendReceipt { + const SendReceipt(this.id, this.remaining); + final String id; + final Duration remaining; +} + +class ComposeDraft { + const ComposeDraft({ + required this.accountId, + required this.to, + required this.subject, + required this.body, + }); + final String accountId; + final String to; + final String subject; + final String body; +} + +class SendOutcome { + const SendOutcome({required this.status, this.error, this.draft}); + final String status; + final String? error; + final ComposeDraft? draft; +} + final mailApiClientProvider = Provider((ref) { return MailApiClient( baseUrl: resolveMailApiBaseUrl(), @@ -195,8 +221,8 @@ class MailApiClient { }); } - /// Queues the mail on the server and returns the id used to cancel it. - Future sendMail({ + /// Queues the mail on the server; the receipt carries the id and the server's send deadline. + Future sendMail({ required String accountId, required List to, required String subject, @@ -210,16 +236,38 @@ class MailApiClient { 'text': body, 'delaySeconds': delaySeconds, }); - return (response.data as Map)['id'] as String; + final data = response.data as Map; + // remaining = sendAt - server now, so client clock skew and upload time do not matter. + final remaining = DateTime.parse(data['sendAt'] as String) + .difference(DateTime.parse(data['now'] as String)); + return SendReceipt(data['id'] as String, remaining); } - /// Returns false when the mail was already sent. - Future cancelSend(String id) async { + /// Returns the resulting status: 'cancelled', or why it could not be cancelled. + Future cancelSend(String id) async { final response = await _dio.post( '/mail/send/$id/cancel', options: Options(validateStatus: (code) => code == 200 || code == 409), ); - return response.statusCode == 200; + return (response.data as Map)['status'] as String; + } + + Future fetchSendOutcome(String id) async { + final response = await _dio.get('/mail/send/$id'); + final data = response.data as Map; + final draft = data['draft'] as Map?; + return SendOutcome( + status: data['status'] as String, + error: data['error'] as String?, + draft: draft == null + ? null + : ComposeDraft( + accountId: draft['accountId'] as String, + to: (draft['to'] as List).cast().join(', '), + subject: draft['subject'] as String? ?? '', + body: draft['text'] as String? ?? '', + ), + ); } } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart new file mode 100644 index 0000000..fdfc944 --- /dev/null +++ b/apps/client/test/send_failure_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:daily_postbox/features/message/compose_page.dart'; +import 'package:daily_postbox/services/mail_api_client.dart'; + +const _draft = ComposeDraft( + accountId: 'a1', + to: 'x@example.com, y@example.com', + subject: 'Hello', + body: 'Body text', +); + +class _PollApi extends MailApiClient { + _PollApi(this.outcomes) : super(baseUrl: 'http://127.0.0.1:1'); + final List outcomes; + int calls = 0; + + @override + Future fetchSendOutcome(String id) async => + outcomes[calls++ < outcomes.length ? calls - 1 : outcomes.length - 1]; +} + +void main() { + const receipt = SendReceipt('id', Duration.zero); + const tick = Duration(milliseconds: 1); + + test('polls past sending and returns the failed outcome with its draft', () async { + final api = _PollApi([ + const SendOutcome(status: 'pending'), + const SendOutcome(status: 'sending'), + const SendOutcome(status: 'failed', error: 'auth', draft: _draft), + ]); + final outcome = await awaitSendOutcome(api, receipt, interval: tick); + expect(outcome?.error, 'auth'); + expect(outcome?.draft?.subject, 'Hello'); + expect(api.calls, 3); + }); + + test('stops quietly once the mail is sent', () async { + final api = _PollApi([const SendOutcome(status: 'sent')]); + expect(await awaitSendOutcome(api, receipt, interval: tick), isNull); + expect(api.calls, 1); + }); + + testWidgets('composer reopens prefilled with the failed draft', (tester) async { + await tester.pumpWidget(ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => const []), + ], + child: const MaterialApp(home: ComposePage(initialDraft: _draft)), + )); + await tester.pump(); + expect(find.text('x@example.com, y@example.com'), findsOneWidget); + expect(find.text('Hello'), findsOneWidget); + expect(find.text('Body text'), findsOneWidget); + }); +} diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index efa76a2..03790ae 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -365,16 +365,25 @@ export async function registerRoutes( return reply.code(404).send({ error: "Account not found" }); } - let id: string; + let queued: { id: string; sendAt: Date }; try { - id = sendQueue.enqueue(account, draft, delaySeconds); + queued = sendQueue.enqueue(account, draft, delaySeconds); } catch (error) { if (error instanceof SendQueueFullError) { return reply.code(429).send({ error: "Too many pending sends" }); } throw error; } - return reply.code(202).send({ id, delaySeconds }); + return reply + .code(202) + .send({ id: queued.id, delaySeconds, sendAt: queued.sendAt.toISOString(), now: new Date().toISOString() }); + }); + + app.get("/mail/send/:id", async (request, reply) => { + const { id } = request.params as { id: string }; + const info = sendQueue.status(id); + if (!info) return reply.code(404).send({ error: "Send request not found" }); + return info; }); app.post("/mail/send/:id/cancel", async (request, reply) => { diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts index 4e13924..51863ef 100644 --- a/apps/server/src/mail/SendQueue.ts +++ b/apps/server/src/mail/SendQueue.ts @@ -5,7 +5,15 @@ import type { MailSender } from "./MailSender.js"; export const undoDelaySeconds = [0, 5, 10, 20, 30] as const; export const defaultUndoDelaySeconds = 5; -export type SendStatus = "pending" | "sent" | "failed" | "cancelled"; +export type SendStatus = "pending" | "sending" | "sent" | "failed" | "cancelled"; + +export interface SendStatusInfo { + status: SendStatus; + sendAt: string; + error?: string; + /** Only for failed sends, so the client can reopen the draft. */ + draft?: OutgoingMessageDraft; +} export interface SendQueueLimits { maxEntries: number; @@ -29,6 +37,9 @@ interface Entry { accountId: string; settled: boolean; status: SendStatus; + sendAt: Date; + draft: OutgoingMessageDraft; + error?: string; timer?: NodeJS.Timeout; sending?: Promise; run: () => Promise; @@ -65,7 +76,11 @@ export class SendQueue { else this.activeSends--; } - enqueue(account: MailAccount, draft: OutgoingMessageDraft, delaySeconds: number): string { + enqueue( + account: MailAccount, + draft: OutgoingMessageDraft, + delaySeconds: number + ): { id: string; sendAt: Date } { if (this.entries.size >= this.limits.maxEntries) throw new SendQueueFullError(); let pendingForAccount = 0; for (const e of this.entries.values()) { @@ -78,18 +93,22 @@ export class SendQueue { accountId: account.id, settled: false, status: "pending", + sendAt: new Date(Date.now() + delaySeconds * 1000), + draft, run: () => { // flush() during an in-flight send must await the same promise, never send twice. if (entry.sending) return entry.sending; if (entry.status !== "pending") return Promise.resolve(); clearTimeout(entry.timer); - entry.status = "sent"; + entry.status = "sending"; entry.sending = (async () => { await this.acquire(); try { await this.sender.send(account, draft); + entry.status = "sent"; } catch (error) { entry.status = "failed"; + entry.error = error instanceof Error ? error.message : String(error); this.onError(error); } finally { this.release(); @@ -102,7 +121,19 @@ export class SendQueue { }; entry.timer = setTimeout(() => void entry.run(), delaySeconds * 1000); this.entries.set(id, entry); - return id; + return { id, sendAt: entry.sendAt }; + } + + /** Result of a queued send; failed entries keep their draft until retention ends. */ + status(id: string): SendStatusInfo | undefined { + const entry = this.entries.get(id); + if (!entry) return undefined; + const info: SendStatusInfo = { status: entry.status, sendAt: entry.sendAt.toISOString() }; + if (entry.status === "failed") { + info.error = entry.error; + info.draft = entry.draft; + } + return info; } private expire(id: string): void { diff --git a/apps/server/test/sendQueue.test.ts b/apps/server/test/sendQueue.test.ts index 911caf2..486882f 100644 --- a/apps/server/test/sendQueue.test.ts +++ b/apps/server/test/sendQueue.test.ts @@ -93,7 +93,7 @@ test("flush awaits an in-flight send without sending twice", async () => { test("cancelled entries are removed after retention", async () => { const queue = new SendQueue({ send: async () => undefined } as never, undefined, 10); - const id = queue.enqueue({} as MailAccount, {} as never, 30); + const { id } = queue.enqueue({} as MailAccount, {} as never, 30); assert.equal(queue.cancel(id), "cancelled"); await new Promise((r) => setTimeout(r, 40)); assert.equal(queue.cancel(id), undefined); @@ -137,3 +137,55 @@ test("concurrent SMTP sends are capped and waiting entries still go out", async assert.equal(peak, 2); assert.equal(running, 0); }); + +test("enqueue response carries the server sendAt", async () => { + const { post, sendQueue } = await setup(); + const before = Date.now(); + const body = (await post(30)).json(); + assert.equal(Date.parse(body.sendAt) - Date.parse(body.now), 30_000); + assert.ok(Date.parse(body.now) >= before); + await sendQueue.flush(); +}); + +test("failed send keeps its draft and error for status polling; cancel reports failed", async () => { + const sender = { send: async () => { throw new Error("535 auth failed"); } }; + const errors: unknown[] = []; + const sendQueue = new SendQueue(sender as never, (e) => errors.push(e)); + const accounts = new InMemoryAccountRepository(); + const now = new Date(); + await accounts.addAccount({ id: "account-1", userId: "u", providerId: "naver", emailAddress: "u@example.com", + authMode: "app-password", incomingProtocol: "imap", encryptedSecretRef: "x", syncStatus: "idle", + createdAt: now, updatedAt: now } as MailAccount); + const app = Fastify(); + await registerRoutes(app, { accounts, sender: sender as never, sendQueue } as never); + const { id } = (await app.inject({ method: "POST", url: "/mail/send", + payload: { accountId: "account-1", to: ["a@example.com"], subject: "hi", text: "body", delaySeconds: 0 } })).json(); + await new Promise((r) => setTimeout(r, 30)); + const res = await app.inject({ method: "GET", url: `/mail/send/${id}` }); + assert.equal(res.statusCode, 200); + const info = res.json(); + assert.equal(info.status, "failed"); + assert.equal(info.error, "535 auth failed"); + assert.equal(info.draft.subject, "hi"); + assert.equal(info.draft.text, "body"); + assert.equal(errors.length, 1); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 409); + assert.equal(cancel.json().status, "failed"); + assert.equal((await app.inject({ method: "GET", url: "/mail/send/nope" })).statusCode, 404); +}); + +test("status goes pending, sending, sent and hides the draft on success", async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const queue = new SendQueue({ send: () => gate } as never); + const { id } = queue.enqueue({} as MailAccount, { subject: "x" } as never, 0.01); + assert.equal(queue.status(id)?.status, "pending"); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(queue.status(id)?.status, "sending"); + release(); + await queue.flush(); + const info = queue.status(id); + assert.equal(info?.status, "sent"); + assert.equal(info?.draft, undefined); +}); From ecb4be16778554173541ca2f1aa05c8b660e6ebb Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:09:41 +0900 Subject: [PATCH 05/12] =?UTF-8?q?=EB=B0=9C=EC=86=A1=20=EA=B2=B0=EA=B3=BC?= =?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=EB=A5=BC=20=EC=B5=9C=EB=8C=80=205?= =?UTF-8?q?=EB=B6=84=20=EB=B0=B1=EC=98=A4=ED=94=84=EB=A1=9C=20=EC=9C=A0?= =?UTF-8?q?=EC=A7=80=ED=95=98=EA=B3=A0,=20=EB=B3=B5=EA=B5=AC=20=EC=B4=88?= =?UTF-8?q?=EC=95=88=EC=9D=80=20=EC=83=88=20=EC=9E=91=EC=84=B1=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=20=EC=9D=B8=EC=8A=A4=ED=84=B4=EC=8A=A4=EB=A1=9C=20?= =?UTF-8?q?=EC=97=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - awaitSendOutcome: pending/sending인 동안 2초부터 15초까지 백오프하며 5분까지 조회 - SendQueue 결과 보관 기본값 60초에서 10분으로 늘려 클라이언트 조회 범위 이상으로 맞춤 - 다시 작성 라우트에 초안별 ObjectKey를 줘 이미 열린 작성 화면 상태를 재사용하지 않음 - 회귀 테스트 추가 --- apps/client/lib/core/app_router.dart | 2 ++ .../lib/features/message/compose_page.dart | 16 ++++++--- apps/client/test/send_failure_test.dart | 33 +++++++++++++++++++ apps/server/src/mail/SendQueue.ts | 2 +- 4 files changed, 47 insertions(+), 6 deletions(-) diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index bba2bb7..d20065c 100644 --- a/apps/client/lib/core/app_router.dart +++ b/apps/client/lib/core/app_router.dart @@ -49,6 +49,8 @@ final appRouterProvider = Provider((ref) { pageBuilder: (context, state) => _verticalPage( state: state, child: ComposePage( + // A recovered draft gets its own page state so an open composer is not reused or clobbered. + key: state.extra is ComposeDraft ? ObjectKey(state.extra) : null, initialAccountId: state.pathParameters['accountId'], initialDraft: state.extra as ComposeDraft?, ), diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index f49a94a..14fe22f 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -212,23 +212,29 @@ Future _reportFailure( )); } -/// Waits out the undo window, then polls a few times. Returns the outcome only when the send failed. +/// Waits out the undo window, then polls with backoff while the send is pending/sending, up to [maxWait]. +/// Returns the outcome only when the send failed. Future awaitSendOutcome( MailApiClient client, SendReceipt receipt, { Duration interval = const Duration(seconds: 2), - int attempts = 10, + Duration maxInterval = const Duration(seconds: 15), + Duration maxWait = const Duration(minutes: 5), }) async { if (receipt.remaining > Duration.zero) await Future.delayed(receipt.remaining); - for (var i = 0; i < attempts; i++) { - await Future.delayed(interval); + var waited = Duration.zero; + var delay = interval; + while (waited < maxWait) { + await Future.delayed(delay); + waited += delay; try { final outcome = await client.fetchSendOutcome(receipt.id); if (outcome.status == 'failed') return outcome; if (outcome.status == 'sent' || outcome.status == 'cancelled') return null; } catch (_) { - // Transient error or expired entry: try again, then give up quietly. + // Transient error or expired entry: keep trying until maxWait. } + delay = delay * 2 > maxInterval ? maxInterval : delay * 2; } return null; } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index fdfc944..89e1512 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -56,4 +56,37 @@ void main() { expect(find.text('Hello'), findsOneWidget); expect(find.text('Body text'), findsOneWidget); }); + + test('keeps polling past 10 tries while still sending, until failure', () async { + final api = _PollApi([ + for (var i = 0; i < 25; i++) const SendOutcome(status: 'sending'), + const SendOutcome(status: 'failed', error: 'late', draft: _draft), + ]); + final outcome = await awaitSendOutcome(api, receipt, + interval: tick, maxInterval: tick, maxWait: const Duration(seconds: 5)); + expect(outcome?.error, 'late'); + expect(api.calls, 26); + }); + + test('gives up after maxWait while still pending', () async { + final api = _PollApi([const SendOutcome(status: 'pending')]); + expect( + await awaitSendOutcome(api, receipt, + interval: tick, maxInterval: tick, maxWait: const Duration(milliseconds: 20)), + isNull); + }); + + testWidgets('recovery draft replaces an already-open composer via new key', (tester) async { + Widget app(Widget page) => ProviderScope( + overrides: [composeAccountsProvider.overrideWith((ref) async => const [])], + child: MaterialApp(home: page), + ); + await tester.pumpWidget(app(const ComposePage())); + await tester.pump(); + expect(find.text('Hello'), findsNothing); + await tester.pumpWidget(app(ComposePage(key: ObjectKey(_draft), initialDraft: _draft))); + await tester.pump(); + expect(find.text('Hello'), findsOneWidget); + expect(find.text('Body text'), findsOneWidget); + }); } diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts index 51863ef..1733a63 100644 --- a/apps/server/src/mail/SendQueue.ts +++ b/apps/server/src/mail/SendQueue.ts @@ -55,7 +55,7 @@ export class SendQueue { constructor( private readonly sender: MailSender, private readonly onError: (error: unknown) => void = () => undefined, - private readonly retainMs = 60_000, + private readonly retainMs = 10 * 60_000, // >= client polling horizon (5 min) limits: Partial = {} ) { this.limits = { ...defaultSendQueueLimits, ...limits }; From 0ca917d58ed82a118efafa4306cdeb19bb6ad912 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:13:23 +0900 Subject: [PATCH 06/12] =?UTF-8?q?=EB=B3=B5=EA=B5=AC=20=EC=9E=91=EC=84=B1?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=EC=9D=84=20=EB=B3=84=EB=8F=84=20=EA=B2=BD?= =?UTF-8?q?=EB=A1=9C=EB=A1=9C=20=EC=8C=93=EC=95=84=20=EC=9E=91=EC=84=B1=20?= =?UTF-8?q?=EC=A4=91=EC=9D=B8=20=EB=A9=94=EC=9D=BC=EC=9D=84=20=EB=B3=B4?= =?UTF-8?q?=EC=A1=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/client/lib/core/app_router.dart | 15 ++++++++-- .../lib/features/message/compose_page.dart | 4 +-- apps/client/test/send_failure_test.dart | 30 ++++++++++++------- 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index d20065c..f167855 100644 --- a/apps/client/lib/core/app_router.dart +++ b/apps/client/lib/core/app_router.dart @@ -49,13 +49,22 @@ final appRouterProvider = Provider((ref) { pageBuilder: (context, state) => _verticalPage( state: state, child: ComposePage( - // A recovered draft gets its own page state so an open composer is not reused or clobbered. - key: state.extra is ComposeDraft ? ObjectKey(state.extra) : null, initialAccountId: state.pathParameters['accountId'], - initialDraft: state.extra as ComposeDraft?, ), ), ), + GoRoute( + // Pushed on top of any open composer so its input survives; popping returns to it. + path: '/compose/recover', + redirect: (context, state) => state.extra is ComposeDraft ? null : '/accounts', + pageBuilder: (context, state) { + final draft = state.extra! as ComposeDraft; + return _verticalPage( + state: state, + child: ComposePage(initialAccountId: draft.accountId, initialDraft: draft), + ); + }, + ), GoRoute( path: '/messages/:id', pageBuilder: (context, state) => _verticalPage( diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 14fe22f..8cb3d93 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -67,7 +67,7 @@ class _ComposePageState extends ConsumerState { AppBar( leading: IconButton( tooltip: strings.close, - onPressed: () => context.go(returnPath), + onPressed: () => context.canPop() ? context.pop() : context.go(returnPath), icon: const Icon(Icons.close), ), title: Text(strings.compose), @@ -207,7 +207,7 @@ Future _reportFailure( duration: const Duration(seconds: 15), action: SnackBarAction( label: strings.rewriteMail, - onPressed: () => router.go('/accounts/${draft.accountId}/compose', extra: draft), + onPressed: () => router.push('/compose/recover', extra: draft), ), )); } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index 89e1512..93ed071 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; import 'package:daily_postbox/features/message/compose_page.dart'; import 'package:daily_postbox/services/mail_api_client.dart'; @@ -76,17 +77,26 @@ void main() { isNull); }); - testWidgets('recovery draft replaces an already-open composer via new key', (tester) async { - Widget app(Widget page) => ProviderScope( - overrides: [composeAccountsProvider.overrideWith((ref) async => const [])], - child: MaterialApp(home: page), - ); - await tester.pumpWidget(app(const ComposePage())); - await tester.pump(); - expect(find.text('Hello'), findsNothing); - await tester.pumpWidget(app(ComposePage(key: ObjectKey(_draft), initialDraft: _draft))); + testWidgets('recovery is stacked: original compose input survives pop', (tester) async { + final router = GoRouter(routes: [ + GoRoute(path: '/', builder: (_, __) => const ComposePage()), + GoRoute( + path: '/compose/recover', + builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [composeAccountsProvider.overrideWith((ref) async => const [])], + child: MaterialApp.router(routerConfig: router), + )); await tester.pump(); + await tester.enterText(find.byType(TextField).first, 'typing in progress'); + router.push('/compose/recover', extra: _draft); + await tester.pumpAndSettle(); expect(find.text('Hello'), findsOneWidget); - expect(find.text('Body text'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('typing in progress'), findsOneWidget); + expect(find.text('Hello'), findsNothing); }); } From 82a8b99d1a0b87ada7b0a388d63062a3c876c621 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:17:37 +0900 Subject: [PATCH 07/12] =?UTF-8?q?=EB=B3=B5=EA=B5=AC=20=EC=9E=91=EC=84=B1?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=EC=97=90=EC=84=9C=20=EB=B0=9C=EC=86=A1?= =?UTF-8?q?=ED=95=9C=20=EB=92=A4=20go=20=EB=8C=80=EC=8B=A0=20pop=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=8F=8C=EC=95=84=EA=B0=80=20=EA=B8=B0=EC=A1=B4=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20=EB=82=B4=EC=9A=A9=EC=9D=84=20=EB=B3=B4?= =?UTF-8?q?=EC=A1=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 별도 push로 쌓은 복구 화면은 발송 성공 후에도 context.go로 스택 전체가 교체되어 아래의 작성 중인 메일이 사라졌다. 쌓인 화면이면 pop하고, 아니면 기존처럼 메일함으로 이동한다. 되돌리기 스낵바와 실패 폴링은 루트 ScaffoldMessenger를 쓰므로 pop 이후에도 유지된다. --- .../lib/features/message/compose_page.dart | 8 ++- apps/client/test/send_failure_test.dart | 65 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 8cb3d93..7ec4236 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -187,7 +187,13 @@ class _ComposePageState extends ConsumerState { // Detached from this page on purpose: the composer closes right after sending. unawaited(_reportFailure(client, receipt, strings, messenger, router)); - if (mounted) context.go('/accounts/$accountId/mail'); + // Pushed pages (recovery compose) pop so the composer underneath keeps its input. + if (!mounted) return; + if (context.canPop()) { + context.pop(); + } else { + context.go('/accounts/$accountId/mail'); + } } } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index 93ed071..9320a1d 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -23,6 +23,24 @@ class _PollApi extends MailApiClient { outcomes[calls++ < outcomes.length ? calls - 1 : outcomes.length - 1]; } +class _SendApi extends MailApiClient { + _SendApi() : super(baseUrl: 'http://127.0.0.1:1'); + + @override + Future sendMail({ + required String accountId, + required List to, + required String subject, + required String body, + int delaySeconds = 5, + }) async => + const SendReceipt('id', Duration(seconds: 5)); + + @override + Future fetchSendOutcome(String id) async => + const SendOutcome(status: 'sent'); +} + void main() { const receipt = SendReceipt('id', Duration.zero); const tick = Duration(milliseconds: 1); @@ -99,4 +117,51 @@ void main() { expect(find.text('typing in progress'), findsOneWidget); expect(find.text('Hello'), findsNothing); }); + + testWidgets('sending from recovery pops back to the original compose with undo snackbar', + (tester) async { + final router = GoRouter(routes: [ + GoRoute(path: '/', builder: (_, __) => const ComposePage()), + GoRoute( + path: '/compose/recover', + builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(_SendApi()), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + await tester.enterText(find.byType(TextField).first, 'typing in progress'); + router.push('/compose/recover', extra: _draft); + await tester.pumpAndSettle(); + expect(find.text('Hello'), findsOneWidget); + + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + + expect(find.text('typing in progress'), findsOneWidget); + expect(find.text('Hello'), findsNothing); + expect(find.byType(SnackBar), findsOneWidget); + expect(find.byType(SnackBarAction), findsOneWidget); + + // Let the snackbar and the detached outcome poll finish before teardown. + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + }); } From 30be1517e48771831ce7e1308d202ee21919b44d Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:21:48 +0900 Subject: [PATCH 08/12] =?UTF-8?q?=EB=B0=9C=EC=86=A1=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=20=EC=B4=88=EC=95=88=EC=9D=84=20=EC=95=B1=20=EB=8B=A8=EC=9C=84?= =?UTF-8?q?=20=EC=83=81=ED=83=9C=EB=A1=9C=20=EB=B3=B4=EA=B4=80=ED=95=98?= =?UTF-8?q?=EA=B3=A0=20'=EB=B0=9C=EC=86=A1=20=EC=8B=A4=ED=8C=A8=20N?= =?UTF-8?q?=EA=B1=B4'=20=EB=B0=B0=EB=84=88=EC=97=90=EC=84=9C=20=EB=8B=A4?= =?UTF-8?q?=EC=8B=9C=20=EC=9E=91=EC=84=B1=C2=B7=EC=82=AD=EC=A0=9C=ED=95=98?= =?UTF-8?q?=EB=8F=84=EB=A1=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/core/i18n/language_controller.dart | 2 + .../lib/features/message/compose_page.dart | 10 ++- .../lib/features/message/failed_sends.dart | 90 +++++++++++++++++++ apps/client/lib/widgets/app_shell.dart | 26 ++++-- apps/client/test/send_failure_test.dart | 88 ++++++++++++++++++ 5 files changed, 205 insertions(+), 11 deletions(-) create mode 100644 apps/client/lib/features/message/failed_sends.dart diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 067e12a..3301630 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -216,6 +216,8 @@ class AppStrings { ? '메일을 보내지 못했습니다: $reason' : 'The mail could not be delivered: $reason'; String get sendFailedShort => _ko ? '발송에 실패했습니다.' : 'Sending failed.'; + String failedSendsCount(int n) => _ko ? '발송 실패 $n건' : '$n failed to send'; + String get deleteFailedSend => _ko ? '삭제' : 'Delete'; String get rewriteMail => _ko ? '다시 작성' : 'Rewrite'; String get undoSendSetting => _ko ? '보내기 취소 시간' : 'Undo send delay'; String get undoSendSettingDescription => _ko diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 7ec4236..1a201cf 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -7,6 +7,7 @@ import 'package:go_router/go_router.dart'; import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; +import 'failed_sends.dart'; final composeAccountsProvider = FutureProvider>((ref) { return ref.watch(mailApiClientProvider).fetchAccounts(); @@ -149,6 +150,7 @@ class _ComposePageState extends ConsumerState { final delay = ref.read(undoSendDelayProvider); final messenger = ScaffoldMessenger.of(context); final router = GoRouter.of(context); + final failedSends = ProviderScope.containerOf(context).read(failedSendsProvider.notifier); final receipt = await client.sendMail( accountId: accountId, to: _toController.text.split(',').map((item) => item.trim()).toList(), @@ -185,7 +187,7 @@ class _ComposePageState extends ConsumerState { } // Detached from this page on purpose: the composer closes right after sending. - unawaited(_reportFailure(client, receipt, strings, messenger, router)); + unawaited(_reportFailure(client, receipt, strings, messenger, router, failedSends)); // Pushed pages (recovery compose) pop so the composer underneath keeps its input. if (!mounted) return; @@ -204,16 +206,20 @@ Future _reportFailure( AppStrings strings, ScaffoldMessengerState messenger, GoRouter router, + FailedSendsNotifier failedSends, ) async { final outcome = await awaitSendOutcome(client, receipt); final draft = outcome?.draft; if (outcome == null || draft == null) return; + final item = FailedSend(id: receipt.id, draft: draft, error: outcome.error ?? ''); + // Also kept in the app-level list: a later send's clearSnackBars() must not lose it. + failedSends.add(item); messenger.showSnackBar(SnackBar( content: Text(strings.sendDeliveryFailed(outcome.error ?? '')), duration: const Duration(seconds: 15), action: SnackBarAction( label: strings.rewriteMail, - onPressed: () => router.push('/compose/recover', extra: draft), + onPressed: () => rewriteFailedSend(router, failedSends, item), ), )); } diff --git a/apps/client/lib/features/message/failed_sends.dart b/apps/client/lib/features/message/failed_sends.dart new file mode 100644 index 0000000..bad1dfa --- /dev/null +++ b/apps/client/lib/features/message/failed_sends.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../services/mail_api_client.dart'; + +class FailedSend { + const FailedSend({required this.id, required this.draft, required this.error}); + final String id; + final ComposeDraft draft; + final String error; +} + +/// App-level so a failed draft outlives the page and snackbars that reported it. +class FailedSendsNotifier extends Notifier> { + @override + List build() => const []; + + void add(FailedSend item) => + state = [...state.where((e) => e.id != item.id), item]; + + void remove(String id) => state = [...state.where((e) => e.id != id)]; +} + +final failedSendsProvider = + NotifierProvider>(FailedSendsNotifier.new); + +/// Reopens a failed draft in the stacked recovery composer and drops it from the list. +void rewriteFailedSend(GoRouter router, FailedSendsNotifier notifier, FailedSend item) { + notifier.remove(item.id); + router.push('/compose/recover', extra: item.draft); +} + +/// Persistent "N failed" indicator; stays until the user rewrites or deletes each draft. +class FailedSendsBanner extends ConsumerWidget { + const FailedSendsBanner({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(failedSendsProvider); + if (items.isEmpty) return const SizedBox.shrink(); + final strings = ref.watch(appStringsProvider); + final notifier = ref.read(failedSendsProvider.notifier); + final scheme = Theme.of(context).colorScheme; + + return Material( + color: scheme.errorContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + strings.failedSendsCount(items.length), + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: scheme.onErrorContainer, + fontWeight: FontWeight.w700, + ), + ), + for (final item in items) + Row( + children: [ + Expanded( + child: Text( + item.draft.subject.isEmpty + ? item.draft.to + : '${item.draft.subject} · ${item.draft.to}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onErrorContainer), + ), + ), + TextButton( + onPressed: () => + rewriteFailedSend(GoRouter.of(context), notifier, item), + child: Text(strings.rewriteMail), + ), + TextButton( + onPressed: () => notifier.remove(item.id), + child: Text(strings.deleteFailedSend), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/apps/client/lib/widgets/app_shell.dart b/apps/client/lib/widgets/app_shell.dart index 6eccb3f..f97fa1d 100644 --- a/apps/client/lib/widgets/app_shell.dart +++ b/apps/client/lib/widgets/app_shell.dart @@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart'; import '../core/i18n/language_controller.dart'; import '../features/accounts/account_providers.dart'; +import '../features/message/failed_sends.dart'; class AppShell extends ConsumerWidget { const AppShell({ @@ -87,15 +88,22 @@ class AppShell extends ConsumerWidget { child: navigation, ) : null, - body: compact - ? child - : Row( - children: [ - SizedBox(width: 284, child: navigation), - const VerticalDivider(width: 1), - Expanded(child: child), - ], - ), + body: Column( + children: [ + const FailedSendsBanner(), + Expanded( + child: compact + ? child + : Row( + children: [ + SizedBox(width: 284, child: navigation), + const VerticalDivider(width: 1), + Expanded(child: child), + ], + ), + ), + ], + ), floatingActionButton: floatingActionButton, ); } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index 9320a1d..80352ae 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -4,7 +4,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:daily_postbox/features/message/compose_page.dart'; +import 'package:daily_postbox/features/accounts/account_providers.dart'; import 'package:daily_postbox/services/mail_api_client.dart'; +import 'package:daily_postbox/widgets/app_shell.dart'; const _draft = ComposeDraft( accountId: 'a1', @@ -42,6 +44,7 @@ class _SendApi extends MailApiClient { } void main() { + _failedSendsTests(); const receipt = SendReceipt('id', Duration.zero); const tick = Duration(milliseconds: 1); @@ -165,3 +168,88 @@ void main() { await tester.pump(const Duration(seconds: 3)); }); } + +class _FailApi extends _SendApi { + @override + Future fetchSendOutcome(String id) async => + const SendOutcome(status: 'failed', error: 'auth', draft: _draft); +} + +void _failedSendsTests() { + Future pumpApp(WidgetTester tester) async { + Widget shell(Widget child) => AppShell(selectedDestinationId: 'x', child: child); + final router = GoRouter(routes: [ + GoRoute( + path: '/', + builder: (_, __) => const ComposePage(initialAccountId: 'a1'), + ), + GoRoute( + path: '/accounts/:id/mail', + builder: (_, __) => shell(const Text('mailbox')), + ), + GoRoute( + path: '/compose/recover', + builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(_FailApi()), + accountsProvider.overrideWith((ref) async => const []), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + return router; + } + + testWidgets('failed draft stays recoverable from banner after snackbars are cleared', + (tester) async { + final router = await pumpApp(tester); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + // Undo window (5s) + first poll (2s), then the failure surfaces. + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + expect(find.text('발송 실패 1건'), findsOneWidget); + expect(find.byType(SnackBarAction), findsOneWidget); + + // A new send does this to the earlier failure snackbar. + ScaffoldMessenger.of(tester.element(find.text('mailbox'))).clearSnackBars(); + await tester.pumpAndSettle(); + expect(find.byType(SnackBar), findsNothing); + expect(find.text('발송 실패 1건'), findsOneWidget); + + await tester.tap(find.text('다시 작성')); + await tester.pumpAndSettle(); + expect(router.state.uri.path, '/compose/recover'); + expect(find.text('Hello'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 1건'), findsNothing); + }); + + testWidgets('banner delete drops the failed draft', (tester) async { + await pumpApp(tester); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + await tester.tap(find.text('삭제')); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 1건'), findsNothing); + }); +} From bf948f75fe9d1b67370da41bbb56c8fc36b77292 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:26:02 +0900 Subject: [PATCH 09/12] =?UTF-8?q?=EB=B0=9C=EC=86=A1=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=20=EB=B0=B0=EB=84=88=EB=A5=BC=20=ED=95=9C=20=EC=A4=84=EB=A1=9C?= =?UTF-8?q?=20=EC=A4=84=EC=9D=B4=EA=B3=A0=20=EB=AA=A9=EB=A1=9D=EC=9D=80=20?= =?UTF-8?q?=EB=86=92=EC=9D=B4=EA=B0=80=20=EC=A0=9C=ED=95=9C=EB=90=9C=20?= =?UTF-8?q?=EB=8C=80=ED=99=94=EC=83=81=EC=9E=90=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EB=B3=B4=EB=8F=84=EB=A1=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 실패 항목이 쌓여도 메일 영역이 밀려나지 않는다. '보기' 대화상자 안에서 스크롤하며 다시 작성·삭제한다. --- .../lib/features/message/failed_sends.dart | 120 ++++++++++++------ apps/client/test/send_failure_test.dart | 86 +++++++++++-- 2 files changed, 157 insertions(+), 49 deletions(-) diff --git a/apps/client/lib/features/message/failed_sends.dart b/apps/client/lib/features/message/failed_sends.dart index bad1dfa..ca6e3b2 100644 --- a/apps/client/lib/features/message/failed_sends.dart +++ b/apps/client/lib/features/message/failed_sends.dart @@ -6,7 +6,8 @@ import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; class FailedSend { - const FailedSend({required this.id, required this.draft, required this.error}); + const FailedSend( + {required this.id, required this.draft, required this.error}); final String id; final ComposeDraft draft; final String error; @@ -24,15 +25,18 @@ class FailedSendsNotifier extends Notifier> { } final failedSendsProvider = - NotifierProvider>(FailedSendsNotifier.new); + NotifierProvider>( + FailedSendsNotifier.new); /// Reopens a failed draft in the stacked recovery composer and drops it from the list. -void rewriteFailedSend(GoRouter router, FailedSendsNotifier notifier, FailedSend item) { +void rewriteFailedSend( + GoRouter router, FailedSendsNotifier notifier, FailedSend item) { notifier.remove(item.id); router.push('/compose/recover', extra: item.draft); } -/// Persistent "N failed" indicator; stays until the user rewrites or deletes each draft. +/// Persistent single-row "N failed" indicator; the list lives in a bounded dialog so the +/// banner never grows and pushes the mail area off screen. class FailedSendsBanner extends ConsumerWidget { const FailedSendsBanner({super.key}); @@ -41,50 +45,92 @@ class FailedSendsBanner extends ConsumerWidget { final items = ref.watch(failedSendsProvider); if (items.isEmpty) return const SizedBox.shrink(); final strings = ref.watch(appStringsProvider); - final notifier = ref.read(failedSendsProvider.notifier); final scheme = Theme.of(context).colorScheme; return Material( color: scheme.errorContainer, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( children: [ - Text( - strings.failedSendsCount(items.length), - style: Theme.of(context).textTheme.labelLarge?.copyWith( - color: scheme.onErrorContainer, - fontWeight: FontWeight.w700, - ), - ), - for (final item in items) - Row( - children: [ - Expanded( - child: Text( - item.draft.subject.isEmpty - ? item.draft.to - : '${item.draft.subject} · ${item.draft.to}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: scheme.onErrorContainer), + Expanded( + child: Text( + strings.failedSendsCount(items.length), + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: scheme.onErrorContainer, + fontWeight: FontWeight.w700, ), - ), - TextButton( - onPressed: () => - rewriteFailedSend(GoRouter.of(context), notifier, item), - child: Text(strings.rewriteMail), - ), - TextButton( - onPressed: () => notifier.remove(item.id), - child: Text(strings.deleteFailedSend), - ), - ], ), + ), + TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => + _FailedSendsDialog(router: GoRouter.of(context)), + ), + child: Text(strings.viewFailedSends), + ), ], ), ), ); } } + +class _FailedSendsDialog extends ConsumerWidget { + const _FailedSendsDialog({required this.router}); + final GoRouter router; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(failedSendsProvider); + final strings = ref.watch(appStringsProvider); + final notifier = ref.read(failedSendsProvider.notifier); + return AlertDialog( + title: Text(strings.failedSendsCount(items.length)), + content: SizedBox( + width: 480, + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, i) { + final item = items[i]; + return Row( + children: [ + Expanded( + child: Text( + item.draft.subject.isEmpty + ? item.draft.to + : '${item.draft.subject} · ${item.draft.to}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + TextButton( + onPressed: () { + Navigator.of(context).pop(); + rewriteFailedSend(router, notifier, item); + }, + child: Text(strings.rewriteMail), + ), + TextButton( + onPressed: () { + if (items.length == 1) Navigator.of(context).pop(); + notifier.remove(item.id); + }, + child: Text(strings.deleteFailedSend), + ), + ], + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(strings.close), + ), + ], + ); + } +} diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index 80352ae..de7fdc6 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:daily_postbox/features/message/compose_page.dart'; +import 'package:daily_postbox/features/message/failed_sends.dart'; import 'package:daily_postbox/features/accounts/account_providers.dart'; import 'package:daily_postbox/services/mail_api_client.dart'; import 'package:daily_postbox/widgets/app_shell.dart'; @@ -48,7 +49,8 @@ void main() { const receipt = SendReceipt('id', Duration.zero); const tick = Duration(milliseconds: 1); - test('polls past sending and returns the failed outcome with its draft', () async { + test('polls past sending and returns the failed outcome with its draft', + () async { final api = _PollApi([ const SendOutcome(status: 'pending'), const SendOutcome(status: 'sending'), @@ -66,7 +68,8 @@ void main() { expect(api.calls, 1); }); - testWidgets('composer reopens prefilled with the failed draft', (tester) async { + testWidgets('composer reopens prefilled with the failed draft', + (tester) async { await tester.pumpWidget(ProviderScope( overrides: [ composeAccountsProvider.overrideWith((ref) async => const []), @@ -79,7 +82,8 @@ void main() { expect(find.text('Body text'), findsOneWidget); }); - test('keeps polling past 10 tries while still sending, until failure', () async { + test('keeps polling past 10 tries while still sending, until failure', + () async { final api = _PollApi([ for (var i = 0; i < 25; i++) const SendOutcome(status: 'sending'), const SendOutcome(status: 'failed', error: 'late', draft: _draft), @@ -94,20 +98,26 @@ void main() { final api = _PollApi([const SendOutcome(status: 'pending')]); expect( await awaitSendOutcome(api, receipt, - interval: tick, maxInterval: tick, maxWait: const Duration(milliseconds: 20)), + interval: tick, + maxInterval: tick, + maxWait: const Duration(milliseconds: 20)), isNull); }); - testWidgets('recovery is stacked: original compose input survives pop', (tester) async { + testWidgets('recovery is stacked: original compose input survives pop', + (tester) async { final router = GoRouter(routes: [ GoRoute(path: '/', builder: (_, __) => const ComposePage()), GoRoute( path: '/compose/recover', - builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), ), ]); await tester.pumpWidget(ProviderScope( - overrides: [composeAccountsProvider.overrideWith((ref) async => const [])], + overrides: [ + composeAccountsProvider.overrideWith((ref) async => const []) + ], child: MaterialApp.router(routerConfig: router), )); await tester.pump(); @@ -121,13 +131,15 @@ void main() { expect(find.text('Hello'), findsNothing); }); - testWidgets('sending from recovery pops back to the original compose with undo snackbar', + testWidgets( + 'sending from recovery pops back to the original compose with undo snackbar', (tester) async { final router = GoRouter(routes: [ GoRoute(path: '/', builder: (_, __) => const ComposePage()), GoRoute( path: '/compose/recover', - builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), ), ]); await tester.pumpWidget(ProviderScope( @@ -177,7 +189,8 @@ class _FailApi extends _SendApi { void _failedSendsTests() { Future pumpApp(WidgetTester tester) async { - Widget shell(Widget child) => AppShell(selectedDestinationId: 'x', child: child); + Widget shell(Widget child) => + AppShell(selectedDestinationId: 'x', child: child); final router = GoRouter(routes: [ GoRoute( path: '/', @@ -189,7 +202,8 @@ void _failedSendsTests() { ), GoRoute( path: '/compose/recover', - builder: (_, state) => ComposePage(initialDraft: state.extra as ComposeDraft), + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), ), ]); await tester.pumpWidget(ProviderScope( @@ -216,7 +230,8 @@ void _failedSendsTests() { return router; } - testWidgets('failed draft stays recoverable from banner after snackbars are cleared', + testWidgets( + 'failed draft stays recoverable from banner after snackbars are cleared', (tester) async { final router = await pumpApp(tester); await tester.tap(find.byIcon(Icons.send_outlined)); @@ -233,6 +248,8 @@ void _failedSendsTests() { expect(find.byType(SnackBar), findsNothing); expect(find.text('발송 실패 1건'), findsOneWidget); + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); await tester.tap(find.text('다시 작성')); await tester.pumpAndSettle(); expect(router.state.uri.path, '/compose/recover'); @@ -248,8 +265,53 @@ void _failedSendsTests() { await tester.pumpAndSettle(const Duration(milliseconds: 100)); await tester.pump(const Duration(seconds: 6)); await tester.pump(const Duration(seconds: 3)); + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); await tester.tap(find.text('삭제')); await tester.pumpAndSettle(); expect(find.text('발송 실패 1건'), findsNothing); }); + + testWidgets( + '30 failures stay one compact row; dialog list is bounded and rewrite works', + (tester) async { + tester.view.physicalSize = const Size(800, 500); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final router = await pumpApp(tester); + final container = + ProviderScope.containerOf(tester.element(find.byType(MaterialApp))); + router.go('/accounts/a1/mail'); + await tester.pumpAndSettle(); + for (var i = 0; i < 30; i++) { + container.read(failedSendsProvider.notifier).add(FailedSend( + id: 'f$i', + draft: ComposeDraft( + accountId: 'a1', + to: 't$i@example.com', + subject: 'S$i', + body: 'b'), + error: 'e')); + } + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('발송 실패 30건'), findsOneWidget); + expect(find.text('mailbox'), findsOneWidget); + expect(tester.getRect(find.text('mailbox')).bottom, lessThan(500)); + expect(find.text('다시 작성'), findsNothing); + + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(tester.getRect(find.byType(AlertDialog)).height, + lessThanOrEqualTo(500)); + + await tester.tap(find.text('다시 작성').first); + await tester.pumpAndSettle(); + expect(router.state.uri.path, '/compose/recover'); + expect(find.text('S0'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 29건'), findsOneWidget); + }); } From 4979b1a623607f1d7d5801c2b0df09d36818148e Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:26:14 +0900 Subject: [PATCH 10/12] =?UTF-8?q?=EC=8B=A4=ED=8C=A8=20=EB=AA=A9=EB=A1=9D?= =?UTF-8?q?=20=EB=B3=B4=EA=B8=B0=20=EB=B2=84=ED=8A=BC=20=EB=AC=B8=EA=B5=AC?= =?UTF-8?q?(=ED=95=9C=EA=B5=AD=EC=96=B4=C2=B7=EC=98=81=EC=96=B4)=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/client/lib/core/i18n/language_controller.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 3301630..943ba49 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -217,6 +217,7 @@ class AppStrings { : 'The mail could not be delivered: $reason'; String get sendFailedShort => _ko ? '발송에 실패했습니다.' : 'Sending failed.'; String failedSendsCount(int n) => _ko ? '발송 실패 $n건' : '$n failed to send'; + String get viewFailedSends => _ko ? '보기' : 'View'; String get deleteFailedSend => _ko ? '삭제' : 'Delete'; String get rewriteMail => _ko ? '다시 작성' : 'Rewrite'; String get undoSendSetting => _ko ? '보내기 취소 시간' : 'Undo send delay'; From dc7721ca48e4fe0897b0e6248904de8c66cb2ee4 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:05:14 +0900 Subject: [PATCH 11/12] =?UTF-8?q?=EB=8C=80=EA=B8=B0=20=EC=A4=91=EC=9D=B8?= =?UTF-8?q?=20=EB=B0=9C=EC=86=A1=EC=9D=84=20=EB=AA=A8=EB=91=90=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C=ED=95=A0=20=EC=88=98=20=EC=9E=88=EA=B2=8C=20=ED=95=98?= =?UTF-8?q?=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 취소 대기 시간 안에 두 통을 보내면 새 스낵바가 앞 메일의 '보내기 취소'를 지워 서버에 대기 중인 메일을 취소할 수 없었다. 앱 전역 대기 발송 목록과 건수 배너를 두고 목록에서 각 건을 취소할 수 있게 했다. 서버 발송 시각이 지나면 목록에서 뺀다. --- .../lib/core/i18n/language_controller.dart | 2 + .../lib/features/message/compose_page.dart | 32 ++-- .../lib/features/message/pending_sends.dart | 163 ++++++++++++++++++ apps/client/lib/widgets/app_shell.dart | 2 + apps/client/test/send_failure_test.dart | 90 ++++++++++ 5 files changed, 273 insertions(+), 16 deletions(-) create mode 100644 apps/client/lib/features/message/pending_sends.dart diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 943ba49..71a1caa 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -217,6 +217,8 @@ class AppStrings { : 'The mail could not be delivered: $reason'; String get sendFailedShort => _ko ? '발송에 실패했습니다.' : 'Sending failed.'; String failedSendsCount(int n) => _ko ? '발송 실패 $n건' : '$n failed to send'; + String pendingSendsCount(int n) => _ko ? '보내기 대기 $n건' : '$n waiting to send'; + String get viewPendingSends => _ko ? '보기' : 'View'; String get viewFailedSends => _ko ? '보기' : 'View'; String get deleteFailedSend => _ko ? '삭제' : 'Delete'; String get rewriteMail => _ko ? '다시 작성' : 'Rewrite'; diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 1a201cf..0c2a753 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -8,6 +8,7 @@ import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; import 'failed_sends.dart'; +import 'pending_sends.dart'; final composeAccountsProvider = FutureProvider>((ref) { return ref.watch(mailApiClientProvider).fetchAccounts(); @@ -150,7 +151,9 @@ class _ComposePageState extends ConsumerState { final delay = ref.read(undoSendDelayProvider); final messenger = ScaffoldMessenger.of(context); final router = GoRouter.of(context); - final failedSends = ProviderScope.containerOf(context).read(failedSendsProvider.notifier); + final container = ProviderScope.containerOf(context); + final failedSends = container.read(failedSendsProvider.notifier); + final pendingSends = container.read(pendingSendsProvider.notifier); final receipt = await client.sendMail( accountId: accountId, to: _toController.text.split(',').map((item) => item.trim()).toList(), @@ -160,28 +163,25 @@ class _ComposePageState extends ConsumerState { ); // The countdown comes from the server's deadline: show immediately (not behind - // older snackbars) and expire when the server actually sends. + // older snackbars) and expire when the server actually sends. Earlier sends stay + // cancellable from the app-level pending list after clearSnackBars(). if (delay > 0 && receipt.remaining > Duration.zero) { + pendingSends.add( + PendingSend( + id: receipt.id, + to: _toController.text, + subject: _subjectController.text, + ), + receipt.remaining, + ); messenger.clearSnackBars(); messenger.showSnackBar(SnackBar( content: Text(strings.mailSending), duration: receipt.remaining, action: SnackBarAction( label: strings.undoSend, - onPressed: () async { - String result; - try { - final status = await client.cancelSend(receipt.id); - result = switch (status) { - 'cancelled' => strings.sendCancelled, - 'failed' => strings.sendFailedShort, - _ => strings.sendAlreadySent, - }; - } catch (_) { - result = strings.sendCancelFailed; - } - messenger.showSnackBar(SnackBar(content: Text(result))); - }, + onPressed: () => cancelPendingSend( + client, strings, messenger, pendingSends, receipt.id), ), )); } diff --git a/apps/client/lib/features/message/pending_sends.dart b/apps/client/lib/features/message/pending_sends.dart new file mode 100644 index 0000000..a4f2ef1 --- /dev/null +++ b/apps/client/lib/features/message/pending_sends.dart @@ -0,0 +1,163 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../services/mail_api_client.dart'; + +class PendingSend { + const PendingSend({required this.id, required this.to, required this.subject}); + final String id; + final String to; + final String subject; +} + +/// App-level list of sends still inside the undo window, so a newer send's snackbar +/// never takes away the way to cancel an earlier one. +class PendingSendsNotifier extends Notifier> { + final _timers = {}; + + @override + List build() { + ref.onDispose(() { + for (final t in _timers.values) { + t.cancel(); + } + }); + return const []; + } + + /// Drops the item by itself once the server deadline passes. + void add(PendingSend item, Duration remaining) { + _timers[item.id]?.cancel(); + _timers[item.id] = Timer(remaining, () => remove(item.id)); + state = [...state.where((e) => e.id != item.id), item]; + } + + void remove(String id) { + _timers.remove(id)?.cancel(); + state = [...state.where((e) => e.id != id)]; + } +} + +final pendingSendsProvider = + NotifierProvider>( + PendingSendsNotifier.new); + +/// Cancels on the server, drops the item, and reports the result in a snackbar. +Future cancelPendingSend( + MailApiClient client, + AppStrings strings, + ScaffoldMessengerState messenger, + PendingSendsNotifier pending, + String id, +) async { + String result; + try { + final status = await client.cancelSend(id); + result = switch (status) { + 'cancelled' => strings.sendCancelled, + 'failed' => strings.sendFailedShort, + _ => strings.sendAlreadySent, + }; + pending.remove(id); + } catch (_) { + result = strings.sendCancelFailed; + } + messenger.showSnackBar(SnackBar(content: Text(result))); +} + +/// Single-row "N waiting" indicator; each send can be cancelled from its dialog. +class PendingSendsBanner extends ConsumerWidget { + const PendingSendsBanner({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(pendingSendsProvider); + if (items.isEmpty) return const SizedBox.shrink(); + final strings = ref.watch(appStringsProvider); + final scheme = Theme.of(context).colorScheme; + + return Material( + color: scheme.secondaryContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Expanded( + child: Text( + strings.pendingSendsCount(items.length), + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: scheme.onSecondaryContainer, + fontWeight: FontWeight.w700, + ), + ), + ), + TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => _PendingSendsDialog( + messenger: ScaffoldMessenger.of(context)), + ), + child: Text(strings.viewPendingSends), + ), + ], + ), + ), + ); + } +} + +class _PendingSendsDialog extends ConsumerWidget { + const _PendingSendsDialog({required this.messenger}); + final ScaffoldMessengerState messenger; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(pendingSendsProvider); + final strings = ref.watch(appStringsProvider); + final notifier = ref.read(pendingSendsProvider.notifier); + final client = ref.read(mailApiClientProvider); + return AlertDialog( + title: Text(strings.pendingSendsCount(items.length)), + content: SizedBox( + width: 480, + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, i) { + final item = items[i]; + return Row( + children: [ + Expanded( + child: Text( + item.subject.isEmpty + ? item.to + : '${item.subject} · ${item.to}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + TextButton( + onPressed: () { + if (items.length == 1) Navigator.of(context).pop(); + cancelPendingSend( + client, strings, messenger, notifier, item.id); + }, + child: Text(strings.undoSend), + ), + ], + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(strings.close), + ), + ], + ); + } +} diff --git a/apps/client/lib/widgets/app_shell.dart b/apps/client/lib/widgets/app_shell.dart index f97fa1d..ae25f04 100644 --- a/apps/client/lib/widgets/app_shell.dart +++ b/apps/client/lib/widgets/app_shell.dart @@ -5,6 +5,7 @@ import 'package:go_router/go_router.dart'; import '../core/i18n/language_controller.dart'; import '../features/accounts/account_providers.dart'; import '../features/message/failed_sends.dart'; +import '../features/message/pending_sends.dart'; class AppShell extends ConsumerWidget { const AppShell({ @@ -90,6 +91,7 @@ class AppShell extends ConsumerWidget { : null, body: Column( children: [ + const PendingSendsBanner(), const FailedSendsBanner(), Expanded( child: compact diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index de7fdc6..26ab209 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -46,6 +46,7 @@ class _SendApi extends MailApiClient { void main() { _failedSendsTests(); + _pendingSendsTests(); const receipt = SendReceipt('id', Duration.zero); const tick = Duration(milliseconds: 1); @@ -315,3 +316,92 @@ void _failedSendsTests() { expect(find.text('발송 실패 29건'), findsOneWidget); }); } + +class _UndoApi extends _SendApi { + int sent = 0; + final cancelled = []; + + @override + Future sendMail({ + required String accountId, + required List to, + required String subject, + required String body, + int delaySeconds = 5, + }) async => + SendReceipt('s${++sent}', const Duration(seconds: 30)); + + @override + Future cancelSend(String id) async { + cancelled.add(id); + return 'cancelled'; + } +} + +void _pendingSendsTests() { + testWidgets( + 'two sends in the undo window: the first stays cancellable after the second snackbar', + (tester) async { + final api = _UndoApi(); + final router = GoRouter(routes: [ + GoRoute( + path: '/', + builder: (_, __) => const ComposePage(initialAccountId: 'a1'), + ), + GoRoute( + path: '/accounts/:id/mail', + builder: (_, __) => + const AppShell(selectedDestinationId: 'x', child: Text('mailbox')), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async => const []), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + + for (final subject in ['First', 'Second']) { + router.go('/'); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).at(1), subject); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + } + // Only the newest snackbar is visible; both sends are listed. + expect(find.byType(SnackBarAction), findsOneWidget); + expect(find.text('보내기 대기 2건'), findsOneWidget); + + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + await tester.tap(find + .descendant(of: find.byType(AlertDialog), matching: find.text('보내기 취소')) + .first); + await tester.pumpAndSettle(); + expect(api.cancelled, ['s1']); + expect(find.text('보내기 대기 1건'), findsWidgets); + await tester.tap(find.text('닫기')); + await tester.pumpAndSettle(); + + // The rest expires with the server deadline. + await tester.pump(const Duration(seconds: 31)); + await tester.pumpAndSettle(); + expect(find.text('보내기 대기 1건'), findsNothing); + await tester.pump(const Duration(seconds: 10)); + }); +} From b15d7c1c61b82d43b82e17e801b992b24648577c Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:08:22 +0900 Subject: [PATCH 12/12] =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EC=B9=B4=EC=9A=B4?= =?UTF-8?q?=ED=8A=B8=EB=8B=A4=EC=9A=B4=EC=97=90=EC=84=9C=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=20=EC=99=95=EB=B3=B5=20=EC=8B=9C=EA=B0=84=20=EB=B9=BC?= =?UTF-8?q?=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 응답이 늦게 도착하면 서버 기준 남은 시간이 그대로 표시돼 실제보다 길게 취소를 안내했다. 요청 시작부터 응답 수신까지 걸린 시간을 빼서 보수적으로 남은 시간을 잡는다. --- apps/client/lib/services/mail_api_client.dart | 7 +++-- apps/client/test/send_failure_test.dart | 31 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 323b1eb..065db13 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -229,6 +229,7 @@ class MailApiClient { required String body, int delaySeconds = 5, }) async { + final elapsed = Stopwatch()..start(); final response = await _dio.post('/mail/send', data: { 'accountId': accountId, 'to': to, @@ -237,9 +238,11 @@ class MailApiClient { 'delaySeconds': delaySeconds, }); final data = response.data as Map; - // remaining = sendAt - server now, so client clock skew and upload time do not matter. + // remaining = sendAt - server now, so client clock skew does not matter. The whole + // round trip is subtracted too: response transit is unknown, so err on the short side. final remaining = DateTime.parse(data['sendAt'] as String) - .difference(DateTime.parse(data['now'] as String)); + .difference(DateTime.parse(data['now'] as String)) - + elapsed.elapsed; return SendReceipt(data['id'] as String, remaining); } diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart index 26ab209..4affc9f 100644 --- a/apps/client/test/send_failure_test.dart +++ b/apps/client/test/send_failure_test.dart @@ -1,3 +1,6 @@ +import 'dart:convert'; +import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -47,6 +50,32 @@ class _SendApi extends MailApiClient { void main() { _failedSendsTests(); _pendingSendsTests(); + + test('undo countdown subtracts the round trip of a slow response', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((req) async { + final now = DateTime.now().toUtc(); + await Future.delayed(const Duration(milliseconds: 400)); + req.response + ..headers.contentType = ContentType.json + ..write(jsonEncode({ + 'id': 'q1', + 'now': now.toIso8601String(), + 'sendAt': now.add(const Duration(seconds: 5)).toIso8601String(), + })); + await req.response.close(); + }); + // flutter_test answers every HTTP request with 400; use a real client here. + final receipt = await HttpOverrides.runWithHttpOverrides( + () => MailApiClient(baseUrl: 'http://127.0.0.1:${server.port}') + .sendMail( + accountId: 'a1', to: ['x@example.com'], subject: '', body: ''), + _RealHttp()); + expect(receipt.remaining, + lessThanOrEqualTo(const Duration(milliseconds: 4600))); + expect(receipt.remaining, greaterThan(Duration.zero)); + }); const receipt = SendReceipt('id', Duration.zero); const tick = Duration(milliseconds: 1); @@ -317,6 +346,8 @@ void _failedSendsTests() { }); } +class _RealHttp extends HttpOverrides {} + class _UndoApi extends _SendApi { int sent = 0; final cancelled = [];