diff --git a/app/Actions/UpdateMessage.php b/app/Actions/UpdateMessage.php new file mode 100644 index 0000000000..43d93f4352 --- /dev/null +++ b/app/Actions/UpdateMessage.php @@ -0,0 +1,81 @@ +urls->first($body); + $sender = $message->user; + + DB::transaction(function () use ($message, $body, $url, $sender): void { + // Read under a lock so overlapping edits serialize: the second one diffs against the first one's + // committed mentions instead of a stale snapshot, and no badge is left behind. + $previousMentions = array_values(Message::query()->whereKey($message->id)->lockForUpdate()->value('mentions') ?? []); + $message->refresh(); + + $linkPreview = $url === null ? null : LinkPreview::query()->firstOrCreate(['url_hash' => hash('sha256', $url)], ['url' => $url]); + + $message->update([ + 'body' => $this->emojiShortcodes->replace($body), + 'mentions' => $this->mentionedUsers->get($body), + 'link_preview_id' => $linkPreview?->id, + 'edited_at' => now(), + ]); + + if ($linkPreview instanceof LinkPreview && $linkPreview->fetched_at === null) { + dispatch(new UnfurlLink($linkPreview))->afterCommit(); + } + + // Mention badges live on a pivot, not in the JSON. Badges are only added for newly mentioned + // recipients and removed for deleted mentions, so a badge the recipient cleared stays cleared. + if ($message->conversation->isOrg()) { + $currentMentions = array_values($message->mentions ?? []); + + $message->mentionedUsers()->detach(array_diff($previousMentions, $currentMentions)); + + $added = array_diff($currentMentions, $previousMentions); + + if ($added !== []) { + $message->mentionedUsers()->attach($message->conversation->participants() + ->whereIn('user_id', $added) + ->where('user_id', '!=', $sender->id) + ->where('visible_from_id', '<', $message->id) + ->whereNotIn('user_id', $sender->idsAcrossBlocks()) + ->whereNotIn('user_id', $sender->mutedBy()->newPivotQuery()->select('muter_id')) + ->pluck('user_id')); + } + } + }); + + event(new UsersUpdated(ConversationParticipant::query()->where('conversation_id', $message->conversation_id)->pluck('user_id'), UserUpdate::Messages, ['conversation' => $message->conversation_id])); + + return $message->refresh()->load(Message::SHOWN_WITH); + } +} diff --git a/app/Http/Controllers/ConversationMessageController.php b/app/Http/Controllers/ConversationMessageController.php index 6eb07ee817..c2b3b84504 100644 --- a/app/Http/Controllers/ConversationMessageController.php +++ b/app/Http/Controllers/ConversationMessageController.php @@ -6,8 +6,11 @@ use App\Actions\CreateConversation; use App\Actions\CreateMessage; +use App\Actions\UpdateMessage; use App\Http\Requests\CreateConversationMessageRequest; use App\Http\Requests\ListConversationMessagesRequest; +use App\Http\Requests\UpdateConversationMessageRequest; +use App\Models\Message; use App\Models\User; use App\Queries\ConversationThreadQuery; use Illuminate\Container\Attributes\CurrentUser; @@ -40,4 +43,9 @@ public function store(CreateConversationMessageRequest $request, #[CurrentUser] return response()->json(['message' => $message], 201); } + + public function update(UpdateConversationMessageRequest $request, User $partner, Message $message, UpdateMessage $action): JsonResponse + { + return response()->json(['message' => $action->handle($message, $request->string('body')->value())]); + } } diff --git a/app/Http/Controllers/OrgMessageController.php b/app/Http/Controllers/OrgMessageController.php index 83bdb18233..d78985d9c9 100644 --- a/app/Http/Controllers/OrgMessageController.php +++ b/app/Http/Controllers/OrgMessageController.php @@ -5,9 +5,12 @@ namespace App\Http\Controllers; use App\Actions\CreateMessage; +use App\Actions\UpdateMessage; use App\Http\Requests\CreateOrgMessageRequest; use App\Http\Requests\ListOrgMessagesRequest; +use App\Http\Requests\UpdateOrgMessageRequest; use App\Models\Conversation; +use App\Models\Message; use App\Models\User; use App\Queries\ConversationThreadQuery; use Illuminate\Container\Attributes\CurrentUser; @@ -40,4 +43,9 @@ public function store(CreateOrgMessageRequest $request, #[CurrentUser] User $use return response()->json(['message' => $message], 201); } + + public function update(UpdateOrgMessageRequest $request, Conversation $org, Message $message, UpdateMessage $action): JsonResponse + { + return response()->json(['message' => $action->handle($message, $request->string('body')->value())]); + } } diff --git a/app/Http/Requests/UpdateConversationMessageRequest.php b/app/Http/Requests/UpdateConversationMessageRequest.php new file mode 100644 index 0000000000..8231c80b5e --- /dev/null +++ b/app/Http/Requests/UpdateConversationMessageRequest.php @@ -0,0 +1,78 @@ +remotes_enabled || $message->event !== null || ! $message->isVisibleTo($user) || $conversation === null || $message->conversation_id !== $conversation->id) { + return Response::denyAsNotFound(); + } + + if ($message->user_id !== $user->id) { + return Response::denyAsNotFound(); + } + + if ($message->voice !== null) { + return Response::deny('Voice notes cannot be edited.'); + } + + if ($message->editExpired()) { + return Response::deny('Messages can only be edited for 3 minutes after pushing.'); + } + + if (! $user->canMessage($partner)) { + return Response::denyAsNotFound(); + } + + return $access->get($user, $partner) === PushAccess::Open + ? Response::allow() + : Response::deny("You can't edit until the request is merged."); + } + + public function authorize(PushAccessQuery $access): Response + { + $user = $this->user(); + assert($user instanceof User); + + $partner = $this->route('partner'); + assert($partner instanceof User); + + $message = $this->route('message'); + assert($message instanceof Message); + + return self::authorization($user, $message, $partner, $access); + } + + /** + * @return array> + */ + public function rules(): array + { + // A caption can be cleared down to nothing, but only where images remain to hold the message up. + $message = $this->route('message'); + $bodyRequired = ! ($message instanceof Message && $message->images()->exists()); + + return [ + 'body' => [$bodyRequired ? 'required' : 'nullable', 'string', 'max:'.Message::MAX_LENGTH], + ]; + } +} diff --git a/app/Http/Requests/UpdateOrgMessageRequest.php b/app/Http/Requests/UpdateOrgMessageRequest.php new file mode 100644 index 0000000000..d3c6bffdd5 --- /dev/null +++ b/app/Http/Requests/UpdateOrgMessageRequest.php @@ -0,0 +1,57 @@ +remotes_enabled || $message->event !== null || ! $message->isVisibleTo($user) || $message->conversation_id !== $org->id || ! ($org->roleOf($user) instanceof OrgRole) => Response::denyAsNotFound(), + $message->user_id !== $user->id => Response::denyAsNotFound(), + $message->voice !== null => Response::deny('Voice notes cannot be edited.'), + $message->editExpired() => Response::deny('Messages can only be edited for 3 minutes after pushing.'), + default => Response::allow(), + }; + } + + public function authorize(): Response + { + $user = $this->user(); + assert($user instanceof User); + + $org = $this->route('org'); + assert($org instanceof Conversation); + + $message = $this->route('message'); + assert($message instanceof Message); + + return self::authorization($user, $message, $org); + } + + /** + * @return array> + */ + public function rules(): array + { + // A caption can be cleared down to nothing, but only where images remain to hold the message up. + $message = $this->route('message'); + $bodyRequired = ! ($message instanceof Message && $message->images()->exists()); + + return [ + 'body' => [$bodyRequired ? 'required' : 'nullable', 'string', 'max:'.Message::MAX_LENGTH], + ]; + } +} diff --git a/app/Models/Message.php b/app/Models/Message.php index 828a3eb6bd..481b842718 100644 --- a/app/Models/Message.php +++ b/app/Models/Message.php @@ -42,10 +42,11 @@ * @property-read MessageVoice|null $voice * @property-read Collection $reactions * @property-read Conversation $conversation + * @property-read CarbonInterface|null $edited_at * @property-read CarbonInterface $created_at * @property-read CarbonInterface $updated_at */ -#[Visible(['id', 'user_id', 'client_id', 'body', 'reply_to_id', 'mentions', 'event', 'subject_id', 'pinned_at', 'created_at', 'user', 'subject', 'linkPreview', 'images', 'voice', 'reactions'])] +#[Visible(['id', 'user_id', 'client_id', 'body', 'reply_to_id', 'mentions', 'event', 'subject_id', 'pinned_at', 'edited_at', 'created_at', 'user', 'subject', 'linkPreview', 'images', 'voice', 'reactions'])] final class Message extends Model { /** @use HasFactory */ @@ -53,12 +54,25 @@ final class Message extends Model public const int MAX_LENGTH = 2000; + /** + * How long after pushing its author may still edit a message, after which it is frozen for good. + */ + public const int EDIT_WINDOW_MINUTES = 3; + /** * What a message is shown with in a thread: its link card, its images, its voice note, its reactions, and the * message it replies to. */ public const array SHOWN_WITH = ['linkPreview', 'images', 'voice', 'reactions', 'replyTo.images', 'replyTo.voice']; + /** + * Whether the message's edit window has closed, freezing it the way the issue asked. + */ + public function editExpired(): bool + { + return $this->created_at->lt(now()->subMinutes(self::EDIT_WINDOW_MINUTES)); + } + /** * @return array */ @@ -77,6 +91,7 @@ public function casts(): array 'subject_id' => 'string', 'reactions_version' => 'integer', 'pinned_at' => 'datetime', + 'edited_at' => 'datetime', 'created_at' => 'datetime', 'updated_at' => 'datetime', ]; diff --git a/database/migrations/2026_11_13_120000_add_edited_at_to_messages_table.php b/database/migrations/2026_11_13_120000_add_edited_at_to_messages_table.php new file mode 100644 index 0000000000..4666e9773d --- /dev/null +++ b/database/migrations/2026_11_13_120000_add_edited_at_to_messages_table.php @@ -0,0 +1,17 @@ +timestamp('edited_at')->nullable()->after('pinned_at'); + }); + } +}; diff --git a/resources/js/components/chat/conversation-thread.tsx b/resources/js/components/chat/conversation-thread.tsx index ca50a64f20..8a76691ff8 100644 --- a/resources/js/components/chat/conversation-thread.tsx +++ b/resources/js/components/chat/conversation-thread.tsx @@ -69,6 +69,7 @@ import { useVoiceNote } from '@/hooks/use-voice-note'; import { ChatRequestError, settleRequest, + editMessage, loadMessage, loadOlderMessages, markThreadRead, @@ -1327,6 +1328,59 @@ function BubbleWithMeta({ onReply !== null && bubble.kind === 'message' ? () => onReply(replyOf(bubble.message)) : null; + const [isEditing, setIsEditing] = useState(false); + const [draft, setDraft] = useState(''); + const [isSaving, setIsSaving] = useState(false); + // Read once per mount: the thread re-renders on every poll, which is plenty fresh for a three-minute window. + const [mountedAt] = useState(() => Date.now()); + // Matches Message::EDIT_WINDOW_MINUTES on the server. + const editWindowMs = 3 * 60 * 1000; + const hasBody = (body: string): boolean => + body !== '' || + (bubble.kind === 'message' && (bubble.message.images?.length ?? 0) > 0); + // The author gets three minutes after pushing, matching the server's edit window. + const canEdit = + isMine && + bubble.kind === 'message' && + hasBody(bubble.message.body) && + bubble.message.event == null && + bubble.message.voice == null && + mountedAt - Date.parse(bubble.message.created_at) < editWindowMs; + const startEditing = (): void => { + if (bubble.kind !== 'message') { + return; + } + + // The affordance is a snapshot, so recheck the window on the way in: the server enforces it either way. + if (Date.parse(bubble.message.created_at) + editWindowMs < Date.now()) { + toast.error('The edit window for this message has closed.'); + + return; + } + + setDraft(bubble.message.body); + setIsEditing(true); + }; + const saveEdit = (): void => { + if (bubble.kind !== 'message' || isSaving) { + return; + } + + const trimmed = draft.trim(); + + if (!hasBody(trimmed) || trimmed === bubble.message.body) { + setIsEditing(false); + + return; + } + + setIsSaving(true); + + void editMessage(target, bubble.message.id, trimmed) + .then(() => setIsEditing(false)) + .catch(() => toast.error('Could not save your edit. Try again.')) + .finally(() => setIsSaving(false)); + }; // Only org messages pin. Contributors see the pin of a pinned one, and can't press it. const pin = target.kind !== 'org' || bubble.kind !== 'message' @@ -1386,6 +1440,7 @@ function BubbleWithMeta({ isMine={isMine} onReply={replyToThis} onReact={toggleTray} + onEdit={canEdit && !isEditing ? startEditing : null} isReacting={isTrayOpen} reactRef={reactButton} trayId={trayId} @@ -1468,7 +1523,7 @@ function BubbleWithMeta({ {bubbleActions} )} - {message.body !== '' && ( + {(message.body !== '' || isEditing) && (
- + {isEditing ? ( +
+