⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix: keep queued writes and validation scoped to their owner
Tin6c767c87b66d
diff --cc apps/web/src/components/providers/auth-provider/index.tsxindex 4f0413024,4f0413024..9a0596ab2--- a/apps/web/src/components/providers/auth-provider/index.tsx+++ b/apps/web/src/components/providers/auth-provider/index.tsx@@@ -6,6 -6,6 +6,7 @@@ importuseRef,} from "react";import { authClient } from "@/lib/auth-client";++import { descriptionSaveQueue } from "@/lib/description-save-queue";import type { User } from "@/types/user";import { LoadingSkeleton } from "../../ui/loading-skeleton";@@@ -28,6 -28,6 +29,13 @@@ function AuthProvider({ children }: Pro// skeleton while those background fetches are pending we'd unmount the// entire route tree on every alt-tab, which tore down the Turnstile// iframe and forced a re-challenge.++ const previousOwner = useRef<string | null | undefined>(undefined);++ useEffect(() => {++ if (isPending || error) return;++ const owner = data?.user.id ?? null;++ if (previousOwner.current !== owner) descriptionSaveQueue.clear();++ previousOwner.current = owner;++ }, [data?.user.id, isPending, error]);const hasLoadedOnce = useRef(false);if (!isPending) {hasLoadedOnce.current = true;diff --cc apps/web/src/components/task/task-description.tsxindex 09cb6abff,8ec2c25c5..c1439c087--- a/apps/web/src/components/task/task-description.tsx+++ b/apps/web/src/components/task/task-description.tsx@@@ -39,6 -39,6 +39,7 @@@ importimport type { MouseEvent as ReactMouseEvent } from "react";import {useCallback,++ useContext,useEffect,useLayoutEffect,useMemo,@@@ -48,6 -47,6 +49,7 @@@} from "react";import { useTranslation } from "react-i18next";import type { Highlighter } from "shiki";++import { AuthContext } from "@/components/providers/auth-provider";import { Button } from "@/components/ui/button";import { Dialog, DialogPopup } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";@@@ -606,16 -606,40 +608,28 @@@ export default function TaskDescription};}, []);- const pendingDescriptionSavesRef = useRef(- new Map<string, ReturnType<typeof setTimeout>>(),++ const ownerId = useContext(AuthContext).user?.id ?? "";++ const ownerIdRef = useRef(ownerId);++ ownerIdRef.current = ownerId;+ const saveState = useSyncExternalStore(+ descriptionSaveQueue.subscribe,- () => descriptionSaveQueue.get(taskId)?.state ?? "saved",++ () => descriptionSaveQueue.get(taskId, ownerId)?.state ?? "saved",);-const scheduleDescriptionSave = useCallback((markdown: string) => {if (!canEditRef.current) return;-const editedTask = taskRef.current;if (!editedTask) return;- descriptionSaveQueue.schedule(editedTask.id, markdown, (description) =>- updateTaskRef.current({ ...editedTask, description }),-- const timers = pendingDescriptionSavesRef.current;- const pending = timers.get(editedTask.id);- if (pending) clearTimeout(pending);-- timers.set(++ descriptionSaveQueue.schedule(+ editedTask.id,- setTimeout(async () => {- timers.delete(editedTask.id);-- const updateTaskFn = updateTaskRef.current;- if (!updateTaskFn) return;-- const latestTask = taskRef.current;- const base = latestTask?.id === editedTask.id ? latestTask : editedTask;-- try {- await updateTaskFn({- ...base,- description: markdown,- });- } catch (error) {- console.error("Failed to update description:", error);- }- }, DESCRIPTION_SAVE_DEBOUNCE_MS),++ markdown,++ (description) =>++ updateTaskRef.current({++ ...(taskRef.current?.id === editedTask.id++ ? taskRef.current++ : editedTask),++ description,++ }),++ ownerIdRef.current,);}, []);@@@ -1036,12 -1055,7 +1050,12 @@@latestSyncedMarkdownRef.current = "";}- const pendingSave = descriptionSaveQueue.get(taskId);- const incomingMarkdown = formatMarkdown(task?.description || "");++ const pendingSave = descriptionSaveQueue.get(taskId, ownerId);+ const incomingMarkdown = formatMarkdown(+ task?.id && pendingSave && pendingSave.state !== "saved"+ ? pendingSave.value+ : task?.description || "",+ );if (!hasHydratedRef.current) {isSyncingExternalContentRef.current = true;latestSyncedMarkdownRef.current = incomingMarkdown;@@@ -1066,7 -1079,7 +1080,7 @@@requestAnimationFrame(() => {isSyncingExternalContentRef.current = false;});- }, [editor, taskId, task?.id, task?.description]);- }, [editor, taskId, task?.description]);++ }, [editor, taskId, task?.id, task?.description, ownerId]);useEffect(() => {if (!editor) return;@@@ -1416,28 -1429,6 +1430,28 @@@onDragLeave={handleShellDragLeave}onDrop={handleShellDrop}>+ {canEdit && (+ <div+ role="status"+ aria-live="polite"+ className="flex items-center gap-2 text-xs text-muted-foreground"+ >+ {saveState === "failed"+ ? t("tasks:detail.editor.saveFailed")+ : saveState === "saved"+ ? t("tasks:detail.editor.saved")+ : t("tasks:detail.editor.saving")}+ {saveState === "failed" && (+ <Button+ size="xs"+ variant="ghost"- onClick={() => descriptionSaveQueue.retry(taskId)}++ onClick={() => descriptionSaveQueue.retry(taskId, ownerId)}+ >+ {t("tasks:detail.editor.retrySave")}+ </Button>+ )}+ </div>+ )}<inputref={imageInputRef}type="file"diff --cc apps/web/src/hooks/mutations/task/use-update-task-description.tsindex baae2acd0,baae2acd0..8d6f420c4--- a/apps/web/src/hooks/mutations/task/use-update-task-description.ts+++ b/apps/web/src/hooks/mutations/task/use-update-task-description.ts@@@ -7,12 -7,12 +7,12 @@@ export function useUpdateTaskDescriptioreturn useMutation({mutationFn: (task: Task) => updateTaskDescription(task.id, task),-- onSuccess: (_, variables) => {++ onSuccess: (updated, variables) => {queryClient.invalidateQueries({queryKey: ["task", variables.id],});queryClient.invalidateQueries({-- queryKey: ["tasks", variables.projectId],++ queryKey: ["tasks", updated.projectId],});queryClient.invalidateQueries({queryKey: ["notifications"],diff --cc apps/web/src/hooks/mutations/use-sign-out.tsindex cd7ba92c1,cd7ba92c1..cf6626a78--- a/apps/web/src/hooks/mutations/use-sign-out.ts+++ b/apps/web/src/hooks/mutations/use-sign-out.ts@@@ -1,6 -1,6 +1,7 @@@import { useMutation } from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";import { getIdToken } from "@/fetchers/oauth/get-id-token";++import { descriptionSaveQueue } from "@/lib/description-save-queue";import { authClient } from "@/lib/auth-client";function useSignOut(idpLogoutUrl?: string | null) {@@@ -8,6 -8,6 +9,7 @@@return useMutation({mutationFn: async () => {++ descriptionSaveQueue.clear();let idToken: string | null = null;if (idpLogoutUrl) {diff --cc apps/web/src/lib/description-save-queue.test.tsindex 78a4cc1a0,000000000..1735638cfmode 100644,000000..100644--- a/apps/web/src/lib/description-save-queue.test.ts+++ b/apps/web/src/lib/description-save-queue.test.ts@@@ -1,50 -1,0 +1,96 @@@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { createDescriptionSaveQueue } from "./description-save-queue";++afterEach(() => vi.useRealTimers());++describe("description save queue", () => {+ it("serializes requests and coalesces edits made while a save is running", async () => {+ vi.useFakeTimers();+ let finish!: () => void;+ const save = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ )+ .mockResolvedValue(undefined);+ const queue = createDescriptionSaveQueue(10);+ queue.schedule("task", "old", save);+ await vi.advanceTimersByTimeAsync(10);+ queue.schedule("task", "middle", save);+ queue.schedule("task", "newest", save);+ await vi.advanceTimersByTimeAsync(20);+ expect(save.mock.calls).toEqual([["old"]]);+ finish();+ await Promise.resolve();+ await Promise.resolve();+ expect(save.mock.calls).toEqual([["old"], ["newest"]]);+ expect(queue.get("task")).toBeUndefined();+ });++ it("retains failed content for a visible retry and keeps task queues independent", async () => {+ vi.useFakeTimers();+ const save = vi+ .fn()+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue(undefined);+ const queue = createDescriptionSaveQueue(10);+ queue.schedule("a", "unsaved", save);+ queue.schedule("b", "other", vi.fn().mockResolvedValue(undefined));+ await vi.advanceTimersByTimeAsync(10);+ expect(queue.get("a")).toMatchObject({ value: "unsaved", state: "failed" });+ expect(queue.get("b")).toBeUndefined();+ queue.retry("a");+ await Promise.resolve();+ expect(save.mock.calls).toEqual([["unsaved"], ["unsaved"]]);+ expect(queue.get("a")).toBeUndefined();+ });+});++++it("sends a newer pending edit even when the older request fails", async () => {++ vi.useFakeTimers();++ let fail!: (error: Error) => void;++ const save = vi++ .fn()++ .mockImplementationOnce(++ () =>++ new Promise((_resolve, reject) => {++ fail = reject;++ }),++ )++ .mockResolvedValue(undefined);++ const queue = createDescriptionSaveQueue(10);++ queue.schedule("task", "old", save);++ await vi.advanceTimersByTimeAsync(10);++ queue.schedule("task", "new", save);++ await vi.advanceTimersByTimeAsync(10);++ fail(new Error("offline"));++ await vi.advanceTimersByTimeAsync(0);++ expect(save.mock.calls).toEqual([["old"], ["new"]]);++ expect(queue.get("task")).toBeUndefined();++});++it("isolates owners and prevents a cleared in-flight request from draining another user's drafts", async () => {++ vi.useFakeTimers();++ let finish!: () => void;++ const oldSave = vi.fn(++ () =>++ new Promise<void>((resolve) => {++ finish = resolve;++ }),++ );++ const newSave = vi.fn().mockResolvedValue(undefined);++ const queue = createDescriptionSaveQueue(10);++ queue.schedule("task", "private draft", oldSave, "alice");++ await vi.advanceTimersByTimeAsync(10);++ queue.schedule("task", "pending private draft", oldSave, "alice");++ expect(queue.get("task", "bob")).toBeUndefined();++ queue.clear();++ queue.schedule("task", "bob's edit", newSave, "bob");++ finish();++ await vi.advanceTimersByTimeAsync(10);++ expect(oldSave).toHaveBeenCalledTimes(1);++ expect(newSave).toHaveBeenCalledExactlyOnceWith("bob's edit");++ expect(queue.get("task", "alice")).toBeUndefined();++});diff --cc apps/web/src/lib/description-save-queue.tsindex ce6970622,000000000..dc36b48c4mode 100644,000000..100644--- a/apps/web/src/lib/description-save-queue.ts+++ b/apps/web/src/lib/description-save-queue.ts@@@ -1,75 -1,0 +1,100 @@@+export type DescriptionSaveState = "saved" | "saving" | "pending" | "failed";++type Entry = {++ ownerId: string;+ value: string;+ save: (value: string) => Promise<unknown>;+ state: DescriptionSaveState;+ timer?: ReturnType<typeof setTimeout>;+ running: boolean;+ version: number;+};++/** One request per task, with pending edits coalesced to the latest value. */+export function createDescriptionSaveQueue(delay = 700) {+ const entries = new Map<string, Entry>();+ const listeners = new Set<() => void>();+ const notify = () => listeners.forEach((listener) => listener());+ const flush = async (id: string) => {+ const entry = entries.get(id);+ if (!entry || entry.running) return;+ if (entry.timer) clearTimeout(entry.timer);+ entry.timer = undefined;+ entry.running = true;+ entry.state = "saving";+ const version = entry.version;+ notify();+ try {+ await entry.save(entry.value);++ if (entries.get(id) !== entry) return;+ entry.running = false;+ if (entry.version !== version) {+ void flush(id);+ } else {+ entries.delete(id);+ notify();+ }- } catch {++ } catch (error) {++ if (entries.get(id) !== entry) return;+ entry.running = false;- entry.state = "failed";- notify();++ console.error("Description save failed", {++ taskId: id,++ errorName: error instanceof Error ? error.name : "UnknownError",++ status:++ error && typeof error === "object" && "status" in error++ ? error.status++ : undefined,++ });++ if (entry.version !== version) void flush(id);++ else {++ entry.state = "failed";++ notify();++ }+ }+ };+ return {- schedule(id: string, value: string, save: Entry["save"]) {- const previous = entries.get(id);++ schedule(id: string, value: string, save: Entry["save"], ownerId = "") {++ const current = entries.get(id);++ if (current?.timer && current.ownerId !== ownerId)++ clearTimeout(current.timer);++ const previous = current?.ownerId === ownerId ? current : undefined;+ if (previous?.timer) clearTimeout(previous.timer);+ const entry = previous ?? {++ ownerId,+ value,+ save,+ state: "pending",+ running: false,+ version: 0,+ };+ entry.value = value;+ entry.save = save;+ entry.version += 1;+ if (!entry.running) entry.state = "pending";+ entry.timer = setTimeout(() => void flush(id), delay);+ entries.set(id, entry);+ notify();+ },- retry(id: string) {- void flush(id);++ retry(id: string, ownerId = "") {++ if (entries.get(id)?.ownerId === ownerId) void flush(id);+ },- get(id: string) {- return entries.get(id);++ get(id: string, ownerId = "") {++ const entry = entries.get(id);++ return entry?.ownerId === ownerId ? entry : undefined;++ },++ clear() {++ for (const entry of entries.values())++ if (entry.timer) clearTimeout(entry.timer);++ entries.clear();++ notify();+ },+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}++export const descriptionSaveQueue = createDescriptionSaveQueue();diff --cc i18n/schema.jsonindex 727fa2e46,727fa2e46..ed1d06540--- a/i18n/schema.json+++ b/i18n/schema.json@@@ -9256,6 -9256,6 +9256,18 @@@"resizeHandle","small"]++ },++ "saved": {++ "type": "string"++ },++ "saving": {++ "type": "string"++ },++ "saveFailed": {++ "type": "string"++ },++ "retrySave": {++ "type": "string"}},"required": [@@@ -9275,7 -9275,7 +9287,11 @@@"languages","embed","mermaid",-- "image"++ "image",++ "saved",++ "saving",++ "saveFailed",++ "retrySave"]}},