Skip to content

fix(platform): serialize saved task attachment changes - #4339

Merged
yannickmonney merged 4 commits into
mainfrom
fix/task-attachment-overlap
Oct 5, 2026
Merged

yannickmonney merged 4 commits into
mainfrom
fix/task-attachment-overlap

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Changes

  • Serialize saved-task upload/save batches and attachment removals in one edit-body queue, including image paste through the same callback.
  • Read the current saved attachment set immediately before each replacement, preserving accepted additions/removals made while an upload was pending even before UI readback.
  • Reset the shared upload hook's committed attachment ref synchronously when draining it, so an immediately following queued batch cannot drain old files again.
  • Add actual modal/attachment/file-input/upload-hook regressions and document their synthetic-boundary coverage. No UI copy, visual layout, backend contract, infrastructure or reserved fix(platform): cut the per-card mount cost of large task boards #4083 board/performance files change.

Verification

  • Main-first source and merged-PR check at a73fab7af confirmed the defect remains.
  • Final unchanged-main comparison: 5 regression failures, 2 passing controls (15 unrelated tests filtered out). Identical tests after fix: 7 passed.
  • One-worker jsdom tests covering the changed files and their task/chat importers: 15 files, 189 tests passed, using existing dependencies and /opt/node/bin/node.
  • Scoped type-aware lint: passed. TypeScript compiler diagnostics on all 4 changed TS/TSX files (with actual router registration/types): zero diagnostics.
  • Scoped formatting check, git diff --check, manual-reference gate and commitlint: passed.
  • No install, local browser/backend stack or live task/blob writes. Upload, query and mutation boundaries are synthetic; cross-session races and live persistence are not claimed. No locale changes are required because copy is unchanged, and existing accessible controls are retained.

Closes #3904

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent exact-head review: REQUEST CHANGES

Head: 5029cfa9f89b15a89c508d2ab78075c688ca94dc (1 commit, tree 751074ba). It has not moved since the dispatch; I re-read it at 11:17Z. Base a73fab7af. git merge-tree with current main ad3cc8304 is clean.
Reviewer: agent #6 53fe2a33, run 17dae659 (TALE-814, manager run 2b2a9fc1). Implementer: Codex #9 b7c66e31, run c1dee6e5 (TALE-325). The two are distinct agents.

What holds

  • The Bug: a slow task upload removes an attachment saved while it was pending #3904 data loss is fixed. With main's task-modal.tsx and use-file-upload.ts swapped in, the PR's 4 modal regressions and its drain test fail (5 failed), and both controls pass. At this head, 22/22 pass.
  • Each replacement starts from fresh data. It reads GET /tasks/:id through the adapter queryFn (no cache) right before writing, inside one queue per edit body. stripPreviews keeps the validator's shape. A failed step toasts once, and the next batch still proceeds.
  • Nothing else moves. There is no copy, locale or backend-contract change. The automation.md paragraph describes this head's design accurately.

B1 (blocking): the queue serializes the upload itself, not only drain → read → replace

onUploadAttachments (task-modal.tsx:1624) runs uploadFiles(files) inside enqueueAttachmentChange. A later selection therefore doesn't reach the upload hook until the earlier batch has uploaded, saved and drained. Three behaviours that main has are lost. The probe below uses the PR's own harness and mocks:

Probe main's sources this head
Q1: re-select a file while its upload is in flight saved once, "Duplicate file" toast saved twice: [prior-ref, slow-ref-1, slow-ref-2], no toast
Q2: a second selection during an upload 2 "Uploading…" rows 1 row: the queued file shows nothing until its turn
Q3: Remove attachment during an unrelated upload written at once (1 write) 0 writes until the upload and its save finish

Fix sketch (tested): keep the queue, but serialize only the drain/read/replace step.

// Uploads overlap, so the hook's reservations keep the duplicate, count and
// size gates across batches; only drain + read + replace is serialized.
const onUploadAttachments = async (files: File[]) => {
  await uploadFiles(files).catch(onMutationError);
  await enqueueAttachmentChange(async () => {
    const added = clearAttachments();
    if (added.length === 0) return;
    const current = await savedAttachments();
    await updateTask.mutateAsync({
      taskId: task._id,
      attachments: stripPreviews([...current, ...added]),
    });
  });
};
  • Results with the sketch: 25/25 pass (the PR's 22 plus Q1–Q3). oxlint --type-aware and oxfmt --check both exit 0.
  • One PR assertion changes. Test 4's expect(upload).toHaveBeenCalledTimes(1) pins upload serialization. Its save-level form, while the first save is held, is await waitFor(() => expect(upload).toHaveBeenCalledTimes(2)); expect(seams.update).toHaveBeenCalledTimes(1);, with the title "does not save the next batch until the preceding save is accepted".
  • Test 1 then covers the real case. With the sketch, the issue's own interleaving (fast saved while slow is pending) actually happens in test 1. At this head, the fast request is only sent after slow finishes.
  • The docs need one change. The automation.md sentence "serialized through upload and save" should be reworded to match.

Closure proof I'd accept: Q1–Q3 pass on a new exact head, and the PR's 7 cases stay green there while still failing on main's sources.

Non-blocking

  • N1: a cross-session window remains. Read and replace are two requests, so a write from another tab or member that lands between them is still overwritten, as the PR states. A server-side add/remove, or a precondition on updateTask, would close it. That belongs in a follow-up.
  • N2: duplicate toast text. A task deleted mid-change throws new Error(tCommon('errors.generic')). failureDetail → readableErrorMessage returns that message, so the toast shows the generic sentence as both title and description. I read this in source and did not run it.
  • N3: test 1's title over-claims. It says "the later upload response is ready first", but at this head the later request is only sent after the first one settles.

Expected conflicts (local merge-tree on this head merged with main)

Ran

All runs use one worker and --project client. Dependencies are the existing ones, hardlinked from a tree with an identical lockfile; Node 24.21.0, Vitest 4.1.11.

Check Result
The PR's targeted files at this head 22/22 pass
Main's 2 sources swapped in, PR tests plus probe 5 failed / 20 passed (both PR controls and Q1–Q3 pass on main)
The probe at this head Q1–Q3 fail
The probe with the sketch and the save-level test 4 25/25 pass
Scoped oxlint --type-aware on the 4 changed TS files exit 0
oxfmt --check exit 0
Scoped tsc --noEmit (the 4 files, ambient types, app/router.tsx) exit 0
commitlint --from a73fab7af --to 5029cfa9f exit 0
git diff --check clean
bun run lint:manual exit 0 (5 trees, 1459 boxes)
CI snapshot at 11:17Z 50 pass, 28 skipping, 0 failing or pending

Unrun

  • No install, browser, E2E, backend stack, live task or blob write, or full suite.
  • Q1–Q3 run in jsdom against synthetic upload, query and write seams, as the PR's tests do.
  • Real-browser feedback for queued files and N1 are unobserved.
  • N2 and the count/size caps come from reading the source.
  • No CI rerun.

Root's rule (08:15Z) applies: B1 overrides ACCEPT until it is independently closed on an exact head, with proof. This review makes no push, merge, CI action or card move, and no decision on the human-captured native review.

Probe: append to the PR test file's harness (everything above its describe) and run with PROBE_LOG=<file> bunx vitest run <probe> --project client --maxWorkers=1
// Review probe (TALE-814, reviewer agent #6): behaviours main has and the
// queued-upload design changes. Not part of the PR.
import { appendFileSync } from 'node:fs';

const log = (line: string) => {
  if (process.env.PROBE_LOG) appendFileSync(process.env.PROBE_LOG, `${line}\n`);
};

describe('review probe: overlapping selections keep main behaviour', () => {
  it('Q1 rejects the same file re-selected while its upload is in flight', async () => {
    const slow = deferred<Response>();
    let calls = 0;
    vi.stubGlobal(
      'fetch',
      vi.fn(() => {
        calls += 1;
        return calls === 1
          ? slow.promise
          : Promise.resolve(Response.json({ storageId: `slow-ref-${calls}` }));
      }),
    );
    const view = openTask();
    await view.user.upload(view.input, file('slow'));
    await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
    await view.user.upload(view.input, file('slow'));
    await act(async () => {
      slow.resolve(Response.json({ storageId: 'slow-ref-1' }));
    });
    await waitFor(() => expect(seams.update).toHaveBeenCalled());
    await new Promise((resolve) => setTimeout(resolve, 300));
    const saved = seams.task?.attachments?.map((entry) => entry.fileId);
    const dupToast = vi
      .mocked(toast)
      .mock.calls.some(([arg]) => /duplicate/i.test(String(arg?.title)));
    log(`Q1 saved=${JSON.stringify(saved)} uploads=${calls} duplicateToast=${dupToast}`);
    expect(saved?.filter((id) => id.startsWith('slow-ref'))).toHaveLength(1);
    expect(dupToast).toBe(true);
  });

  it('Q2 shows an uploading row for a second selection right away', async () => {
    const pending = deferred<Response>();
    vi.stubGlobal(
      'fetch',
      vi.fn(() => pending.promise),
    );
    const view = openTask();
    await view.user.upload(view.input, file('slow'));
    await waitFor(() => expect(screen.getAllByText('Uploading…')).toHaveLength(1));
    await view.user.upload(view.input, file('other'));
    await new Promise((resolve) => setTimeout(resolve, 200));
    const rows = screen.queryAllByText('Uploading…').length;
    log(`Q2 uploadingRows=${rows}`);
    expect(rows).toBe(2);
  });

  it('Q3 sends a removal without waiting for an unrelated upload', async () => {
    const slow = deferred<Response>();
    vi.stubGlobal(
      'fetch',
      vi.fn(() => slow.promise),
    );
    const view = openTask();
    await view.user.upload(view.input, file('slow'));
    await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
    await view.user.click(
      screen.getByRole('button', { name: 'Remove attachment' }),
    );
    await new Promise((resolve) => setTimeout(resolve, 200));
    const writesBeforeUpload = seams.update.mock.calls.length;
    log(`Q3 writesWhileUploadPending=${writesBeforeUpload}`);
    expect(writesBeforeUpload).toBe(1);
  });
});

@yannickmonney

Copy link
Copy Markdown
Contributor Author

ACCEPT — exact-head B1 re-review

Head reviewed: 50d4921d5c4a39663e951ec9cb61c912032f53f3 (PR #4339, fix/task-attachment-overlap). Reviewer: Codex #13 (7155f7ae), independent of implementer Codex #9 (b7c66e31); repair run dd1e4fda / repair 2b7d629f, relocation 88557b6b.

B1 is closed at this head. Q1 (duplicate re-selection produces one attachment and a duplicate toast), Q2 (each overlapping selection gets an Uploading row), and Q3 (removal proceeds without waiting for an unrelated upload) all pass in task-modal.attachments.test.tsx; the full targeted pair passed 25/25 with one worker:

  • use-file-upload.test.ts + task-modal.attachments.test.tsx: 25 passed
  • scoped oxlint --type-aware: passed
  • scoped oxfmt --check: passed

The main-source comparison still has the pre-repair upload-in-the-queue serialization, so the #3904 regressions remain reproducible on main's sources. The relocation commit 88557b6b changes only the placement/text of the automation.md coverage paragraph; no additional repair changes were found.

Read-only CI observation: checks were still settling when reviewed; completed checks observed were green (including Build, Lint, Format, Browser, Unit and Playwright), with Type check/UI/Validate images still pending. I did not push, merge, rerun, or change status.

@yannickmonney
yannickmonney merged commit 734e0a0 into main Oct 5, 2026
@yannickmonney
yannickmonney deleted the fix/task-attachment-overlap branch October 5, 2026 13:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: a slow task upload removes an attachment saved while it was pending

1 participant