Files
multica/packages/core/chat/store.test.ts
Naiyuan Qing 77b309a5ac feat(drafts): unified draft lifecycle + upload ownership inversion (MUL-5181) (#5900)
* feat(drafts): unified draft lifecycle + upload ownership inversion (MUL-5181)

Unify how every composer preserves unsent work, sends, and handles uploads.

L1 foundation (packages/core/drafts):
- createDraftStore factory + self-registering cleanup-registry replacing the
  hand-maintained WORKSPACE_SCOPED_KEYS list; register-all-drafts guarantees
  registration completeness. Fixes the confirmed cross-user draft leak
  (persistence + in-memory) on logout / workspace delete.

L3 send paradigm:
- useComposerSubmit: one await-then-render contract (lock/spin, keep-on-fail,
  clear-on-success, single-flight, submit-time upload-gate), adopted by
  comment/reply/edit, create-issue, quick-create, and chat.

Per-surface:
- Comment/Reply/Edit: attachments moved into the persisted draft.
- Create Issue: draft split into shared/manual/agent/activeMode with
  non-destructive mode switching + migration for old flat drafts.
- Chat: optimistic send converted to await-then-render (kept server-driven
  cancel restore_to_input); chat draft keys registered for cleanup.

L2 upload coordinator (ownership inversion, Linear-validated shape):
- upload-coordinator + DraftUpload placeholder: uploads owned by a module
  coordinator that outlives the component, state persisted in the draft;
  AbortController + abort-on-logout; interrupted-on-reload. Comment surface
  fully wired. Create-issue/chat upload wiring is a documented residual.

Verified: core + views typecheck clean; core 1064 + views 2928 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(drafts): close three review gaps in the unified draft lifecycle (MUL-5181)

1. Logout resurrection: reset in-memory draft stores BEFORE removing their
   persisted keys — each reset is a setState and persist writes it straight
   back under the still-active slug, so the old order re-created the deleted
   keys. The issue draft store's reset is now a full reset including
   lastAssignee, which clearDraft deliberately re-seeds and would otherwise
   hand the previous user's last-picked assignee to the next login.

2. Submit gate blind spot: the composer gate now also reads the draft's
   coordinator-owned upload placeholders (hasUploadingDraft). A composer
   reopened over a still-in-flight upload could previously send past the
   editor-only gate, clearing the draft out from under the settling upload.

3. Attachment binding returns to reference-filtering: a submit binds only
   uploads the body references, so deleting an inline image really unbinds
   it. An upload that settles after its mount died gets its markdown link
   written back into the body instead — via the reopened composer's live
   editor (new ContentEditorRef.insertMarkdownAtEnd) or appended to the
   persisted draft (new appendToDraftContent) — so close-surviving files
   stay visible, deletable, and honestly bound.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): harden upload write-back delivery after independent review

Review of the previous commit (fresh-context reviewer + probe against real
@tiptap/react) found the write-back could still lose a file:

- insertMarkdownAtEnd now returns a boolean: the imperative handle exists
  from first commit but the Tiptap instance arrives in a passive effect, so
  an insert in that window (or after destroy) no-ops. Callers previously
  assumed it landed.
- Write-back is now confirmed delivery (deliverFinishedUpload): insert into
  the live editor and, on success, persist the same body as insurance
  against the debounced emit being dropped by a quick unmount; append to
  the store only when NO composer is mounted (a mounted editor's first emit
  would erase a store-only append); retry while a mounted composer's
  instance is still warming up. Every attempt re-checks the generation
  guard and the body reference.
- mountedRef flips in a layout effect: React nulls the child editor ref in
  the unmount commit, and a settle in the gap before passive cleanup saw
  "mounted" with no editor left to swap.
- uploadAndInsertFile guards editor.isDestroyed after the await: now that
  uploads outlive mounts, the swap/remove paths could dispatch against a
  destroyed EditorView and escape as an unhandled rejection.
- Tests: the reopened-composer test now asserts the editor actually
  received the insert (it previously passed with liveEditors disabled),
  plus a warming-up retry case; the mock editor mirrors isDestroyed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(drafts): roll coordinated uploads out to issue-create and chat (MUL-5181 L2)

Completes the upload-ownership layer for every composer surface. The generic
engine is extracted from the comment implementation into
editor/use-coordinated-uploads (UploadDraftBinding adapter: store-backed
accessors + registry key + body append), and use-comment-uploads becomes a
thin binding over it — behavior unchanged, all comment tests green.

Issue-create (manual + agent panels):
- shared.attachments migrates Attachment[] -> DraftUpload[]; load normalizes
  legacy bare rows to `uploaded` and coerces stale `uploading` to
  `interrupted`.
- Uploads are coordinator-owned: placeholder at pick time, survives dialog
  close, aborts on logout, chips for uploading/failed/interrupted, combined
  gate on Create and both mode-switch actions.
- Write-back targets the body of the MODE that started the upload (manual
  description vs agent prompt); mount-time prune keeps placeholders and drops
  only unreferenced `uploaded` entries.

Chat (tab + floating window):
- inputDraftAttachments migrates to DraftUpload[] with load-time
  normalization; new store ops (add/settle/fail/remove upload, append-to-
  draft) mirror the comment store.
- ChatInput adopts the engine; the upload target is snapshotted at pick time
  via resolveUploadTarget so a file dropped while the editor is pinned to a
  previous session's document files under THAT draft.
- uploadMapRef is gone — the draft's uploads are the single binding source,
  reference-filtered at send. Hosts no longer own transport: onUploadFile
  prop becomes uploadEnabled, and the controller/window drop uploadWithToast.
- commitDraft prunes only `uploaded` entries the body no longer references;
  placeholders survive keystrokes (chips are their only UI).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): harden L2 rollout after independent review

- attachmentToDraftUpload now strips the response-scoped signed download_url
  before the row is persisted (draft uploads survive restarts; a stale
  signature 403s the preview on reopen). Covers comments, issue-create, and
  chat in one place; issue-create's settle reuses the helper, and the
  Signature assertion the rollout had dropped is restored.
- chat's live-editor registry follows the LOADED draft key (reactive mirror
  of editorDraftKeyRef): a settle for draft B must not insert into an editor
  still pinned to draft A's document.
- removeUpload aborts an in-flight request before dropping its placeholder.
- issue-create hasDraft counts only uploaded/uploading entries so a failed
  remnant can't pin the sidebar draft dot forever.
- Tests: mutation-proof coverage for the two placeholder-preservation rules
  (create-issue mount prune, chat commitDraft prune) — both previously
  survived rule inversion; direct core tests for the five new chat store
  upload ops incl. persistence and signed-URL stripping; quick-create test
  gets the editor i18n namespace; dead uploadWithToast scaffolding removed
  from both modal tests; chat-input mock aligned with the real append
  semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): close third-round review gaps in the upload engine

- The live-editor registry registers in a layout effect: chat's adopt swaps
  the editor's document and loaded key synchronously during commit, and a
  passive re-registration one task later left a settle window where the old
  key mapped to an editor already holding another draft's document. The
  registry key is also built only when a binding exists.
- removeUpload aborts only a request THIS surface tracks as `uploading`
  (guarded before the abort), with the comment now honest about the path
  being defensive — no current chip exposes ✕ mid-upload.
- Mutation-proof test for the loaded-key registry rule: a dead mount's
  settle for a pinned draft must insert into the editor HOLDING it, not the
  selected one (verified to fail with the registry keyed by selection).
- hasDraft upload semantics pinned by tests (uploaded/uploading count;
  failed/interrupted remnants don't pin the sidebar dot).
- Dead scaffolding dropped: identity use-file-upload mocks and a redundant
  assertion in the modal tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): stale-submit draft guard + registry layout timing (review BLOCKED items)

Blocker 1 — a submit that outlives its composer may only consume the draft
it submitted (MUL-5181 P0). Every accepted-submit clear is now guarded:
- create-issue / quick-create snapshot the singleton draft's object identity
  at submit; a dead panel clears (and records last-assignee/mode) only if
  the draft is untouched, and never runs close/reset effects. A replaced
  draft B typed after close survives a late success of draft A.
- comment / reply / edit snapshot the per-key draft entry; a dead composer
  clears only the exact entry it submitted.
- chat snapshots the sent slot's value; a dead mount's commitInput clears
  only an unreplaced draft.
Mutation-verified tests for the create panels and comments (guard inverted
=> tests fail), plus untouched-draft control cases.

Blocker 2 — the live-editor registry is now genuinely registered in a
layout effect. The prior commit claimed this fix but a test-time
`git checkout --` discarded the unstaged engine edits before committing;
re-applied: layout registration, binding-gated registry key, and the
tracked-only abort in removeUpload. New registry timing test captures the
registry from a parent layout effect across a key switch — verified to
fail with passive registration.

Also: `multica:chat:selectedProjectId` joins the workspace-scoped cleanup
list (was leaking across logout; flagged as a pre-existing risk).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): mounted submits also clear only the draft they submitted

The stale-submit snapshot guard previously protected only dead composers;
a mounted one cleared unconditionally on success. But the editor stays
interactive during a request (Tiptap cannot toggle editable post-mount), so
text typed while draft A was in flight was wiped by A's success. The guard
is now unconditional across every surface: success consumes exactly the
submitted snapshot, and any later edit survives.

- create-issue / quick-create: the editor's pending debounce is flushed into
  the store BEFORE snapshotting (a late flush of pre-submit typing must not
  read as a mid-flight edit); a touched draft skips clear AND close/reset —
  the dialog stays open on the newer work. Untouched behavior unchanged.
- comment / reply / edit: same flush + snapshot; a touched entry keeps both
  the store draft and the editor content (edit mode stays open on it).
- chat: commitInput's value compare now applies while mounted too, and the
  editor is scrubbed only for an untouched draft.
- use-composer-submit docs no longer claim "editor locked": they state the
  real contract — send affordance locks, edits after submit survive.

Regression tests: mounted mid-flight-edit cases for manual create (incl.
"dialog must not close over draft B"), quick create, comment, and chat,
plus mounted-untouched controls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(drafts): idempotent draft writes so a tab switch cannot resurrect a posted comment

Final-review blocker: the comment/reply visibilitychange/pagehide flush
re-writes IDENTICAL content on every tab switch, and writeDraft minted a
new entry object each call — the stale-submit guard's identity compare then
read a mid-flight tab switch as "edited during the request", kept the
posted comment's draft alive, and left Send enabled for a duplicate.

- writeDraft is now a no-op when content and uploads are unchanged (also
  kills a spurious persist write per tab switch). Regression tests: entry
  identity preserved on identical setDraft (core), and the reproduced
  tab-switch-mid-send scenario clears the posted draft (views) — verified
  to fail with the idempotence removed.
- onAccepted now flushes the editor's pending debounce before judging
  `untouched` on every surface, so typing still inside the debounce window
  counts as a mid-flight edit instead of being scrubbed.
- create-issue records last-assignee/mode from the SUBMITTED values,
  outside the untouched gate — a created issue updates the preference even
  when the dialog stays open on newer edits.
- Stale guard comments corrected in both create panels; the
  use-composer-submit docstring no longer claims project/feedback were
  migrated (they still hand-roll await-then-clear; registered debt).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:10:00 +08:00

406 lines
15 KiB
TypeScript

import { beforeEach, describe, expect, it } from "vitest";
import { createChatStore, DRAFT_NEW_SESSION } from "./store";
import type { StorageAdapter } from "../types";
import type { Attachment } from "../types";
function memStorage(): StorageAdapter {
const m = new Map<string, string>();
return {
getItem: (k) => m.get(k) ?? null,
setItem: (k, v) => {
m.set(k, v);
},
removeItem: (k) => {
m.delete(k);
},
};
}
function makeAttachment(id: string): Attachment {
return {
id,
workspace_id: "ws-1",
issue_id: null,
comment_id: null,
chat_session_id: null,
chat_message_id: null,
uploader_type: "member",
uploader_id: "user-1",
filename: `${id}.png`,
url: `/uploads/${id}.png`,
download_url: `/api/attachments/${id}/download`,
markdown_url: `/api/attachments/${id}/download`,
content_type: "image/png",
size_bytes: 1,
created_at: new Date(0).toISOString(),
};
}
// The pre-MUL-4864 scheme kept one new-chat draft per agent, in `__new__:<id>`
// slots. Those slots have no timestamp, so on upgrade only one can survive:
// the one for the agent the workspace has selected — the draft the user would
// have been shown. The rest were the invisible multi-draft state, and go.
describe("chat store — legacy per-agent new-chat draft migration", () => {
const DRAFTS_KEY = "multica:chat:drafts";
const ATTACHMENTS_KEY = "multica:chat:draft-attachments";
const AGENT_KEY = "multica:chat:selectedAgentId";
it("adopts the selected agent's legacy draft into the single new-chat slot", () => {
const storage = memStorage();
storage.setItem(AGENT_KEY, "agent-1");
storage.setItem(
DRAFTS_KEY,
JSON.stringify({ "__new__:agent-1": "mine", "__new__:agent-2": "other" }),
);
const store = createChatStore({ storage });
expect(store.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "mine" });
});
it("migrates the matching attachments with the text, not another agent's", () => {
const storage = memStorage();
storage.setItem(AGENT_KEY, "agent-1");
storage.setItem(DRAFTS_KEY, JSON.stringify({ "__new__:agent-1": "mine" }));
storage.setItem(
ATTACHMENTS_KEY,
JSON.stringify({
"__new__:agent-1": [makeAttachment("att-mine")],
"__new__:agent-2": [makeAttachment("att-other")],
}),
);
const store = createChatStore({ storage });
// Legacy bare Attachment rows load as `uploaded` entries (MUL-5181 L2).
expect(
store
.getState()
.inputDraftAttachments[DRAFT_NEW_SESSION]?.map((u) =>
u.status === "uploaded" ? u.attachment.id : u.clientUploadId,
),
).toEqual(["att-mine"]);
expect(store.getState().inputDraftAttachments["__new__:agent-2"]).toBeUndefined();
});
it("persists the migration so the legacy slots do not come back on reload", () => {
const storage = memStorage();
storage.setItem(AGENT_KEY, "agent-1");
storage.setItem(
DRAFTS_KEY,
JSON.stringify({ "__new__:agent-1": "mine", "__new__:agent-2": "other" }),
);
createChatStore({ storage });
// A second store reads what the first one wrote — this is the reload.
const reloaded = createChatStore({ storage });
expect(JSON.parse(storage.getItem(DRAFTS_KEY) ?? "{}")).toEqual({ [DRAFT_NEW_SESSION]: "mine" });
expect(reloaded.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "mine" });
});
it("drops every legacy slot when no agent is selected", () => {
const storage = memStorage();
storage.setItem(DRAFTS_KEY, JSON.stringify({ "__new__:agent-1": "a", "__new__:agent-2": "b" }));
const store = createChatStore({ storage });
expect(store.getState().inputDrafts).toEqual({});
expect(storage.getItem(DRAFTS_KEY)).toBeNull();
});
it("leaves real session drafts untouched", () => {
const storage = memStorage();
storage.setItem(AGENT_KEY, "agent-1");
storage.setItem(
DRAFTS_KEY,
JSON.stringify({ "session-a": "draft A", "session-b": "draft B", "__new__:agent-1": "mine" }),
);
const store = createChatStore({ storage });
expect(store.getState().inputDrafts).toEqual({
"session-a": "draft A",
"session-b": "draft B",
[DRAFT_NEW_SESSION]: "mine",
});
});
it("keeps a current-scheme draft rather than overwriting it with a legacy one", () => {
const storage = memStorage();
storage.setItem(AGENT_KEY, "agent-1");
storage.setItem(
DRAFTS_KEY,
JSON.stringify({ [DRAFT_NEW_SESSION]: "current", "__new__:agent-1": "stale" }),
);
const store = createChatStore({ storage });
expect(store.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "current" });
});
it("does not touch storage when there is nothing to migrate", () => {
const storage = memStorage();
storage.setItem(DRAFTS_KEY, JSON.stringify({ [DRAFT_NEW_SESSION]: "typed" }));
const before = storage.getItem(DRAFTS_KEY);
createChatStore({ storage });
expect(storage.getItem(DRAFTS_KEY)).toBe(before);
});
});
describe("chat store — open/closed default", () => {
it("starts closed when no preference is stored", () => {
const store = createChatStore({ storage: memStorage() });
expect(store.getState().isOpen).toBe(false);
});
it("honours an explicit stored 'open' preference", () => {
const storage = memStorage();
storage.setItem("multica:chat:isOpen", "true");
const store = createChatStore({ storage });
expect(store.getState().isOpen).toBe(true);
});
it("persists a toggle so the choice survives reload", () => {
const storage = memStorage();
const store = createChatStore({ storage });
store.getState().setOpen(true);
expect(storage.getItem("multica:chat:isOpen")).toBe("true");
const reloaded = createChatStore({ storage });
expect(reloaded.getState().isOpen).toBe(true);
});
});
describe("chat store — selected project", () => {
it("persists and clears the next chat's project per workspace", () => {
const storage = memStorage();
const store = createChatStore({ storage });
store.getState().setSelectedProjectId("project-1");
expect(storage.getItem("multica:chat:selectedProjectId")).toBe("project-1");
expect(createChatStore({ storage }).getState().selectedProjectId).toBe("project-1");
store.getState().setSelectedProjectId(null);
expect(storage.getItem("multica:chat:selectedProjectId")).toBeNull();
});
});
describe("chat store — draft attachments", () => {
let store: ReturnType<typeof createChatStore>;
beforeEach(() => {
store = createChatStore({ storage: memStorage() });
});
it("deduplicates attachment drafts by id", () => {
store.getState().addInputDraftAttachment("draft-1", makeAttachment("att-1"));
store.getState().addInputDraftAttachment("draft-1", {
...makeAttachment("att-1"),
filename: "updated.png",
});
expect(store.getState().inputDraftAttachments["draft-1"]).toHaveLength(1);
expect(store.getState().inputDraftAttachments["draft-1"]?.[0]?.filename).toBe("updated.png");
});
it("clearInputDraft clears both text and attachment records", () => {
store.getState().setInputDraft("draft-1", "hello");
store.getState().addInputDraftAttachment("draft-1", makeAttachment("att-1"));
store.getState().clearInputDraft("draft-1");
expect(store.getState().inputDrafts["draft-1"]).toBeUndefined();
expect(store.getState().inputDraftAttachments["draft-1"]).toBeUndefined();
});
});
describe("chat store — floating window preference", () => {
it("defaults ON when no preference is stored", () => {
const store = createChatStore({ storage: memStorage() });
expect(store.getState().floatingChatEnabled).toBe(true);
});
it("honours an explicit stored 'false' preference (opt-out)", () => {
const storage = memStorage();
storage.setItem("multica:chat:floatingChatEnabled", "false");
const store = createChatStore({ storage });
expect(store.getState().floatingChatEnabled).toBe(false);
});
it("honours an explicit stored 'true' preference", () => {
const storage = memStorage();
storage.setItem("multica:chat:floatingChatEnabled", "true");
const store = createChatStore({ storage });
expect(store.getState().floatingChatEnabled).toBe(true);
});
it("persists an enable, then collapses an open overlay when disabled again", () => {
const storage = memStorage();
storage.setItem("multica:chat:floatingChatEnabled", "true");
storage.setItem("multica:chat:isOpen", "true");
const store = createChatStore({ storage });
expect(store.getState().floatingChatEnabled).toBe(true);
expect(store.getState().isOpen).toBe(true);
store.getState().setFloatingChatEnabled(false);
expect(store.getState().floatingChatEnabled).toBe(false);
expect(store.getState().isOpen).toBe(false);
expect(storage.getItem("multica:chat:floatingChatEnabled")).toBe("false");
// A fresh store rehydrates the persisted preference.
const reopened = createChatStore({ storage });
expect(reopened.getState().floatingChatEnabled).toBe(false);
store.getState().setFloatingChatEnabled(true);
expect(store.getState().floatingChatEnabled).toBe(true);
expect(storage.getItem("multica:chat:floatingChatEnabled")).toBe("true");
});
});
// The ledger is what makes a durable draft restore (#5219) apply at most once.
// A consume request can be lost — retries exhausted, app closed mid-flight — and
// the row then comes back on the next fetch. Without a record that survives the
// reload, the prompt would be restored into the composer a second time, after
// the user has already sent it.
describe("chat store — applied draft-restore ledger", () => {
it("survives a reload so a lost consume cannot re-offer the restore", () => {
const storage = memStorage();
const store = createChatStore({ storage });
store.getState().markDraftRestoreApplied("restore-1");
expect(store.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
const reloaded = createChatStore({ storage });
expect(reloaded.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
});
it("is idempotent and drops the entry once the row is confirmed gone", () => {
const store = createChatStore({ storage: memStorage() });
store.getState().markDraftRestoreApplied("restore-1");
store.getState().markDraftRestoreApplied("restore-1");
expect(store.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
store.getState().forgetDraftRestoreApplied("restore-1");
expect(store.getState().appliedDraftRestoreIds).toEqual([]);
});
// Every entry in here is an unconfirmed consume: its row is still on the
// server. Evicting one to cap the ledger would re-arm the restore it was
// suppressing — the next fetch offers an already-applied prompt again and the
// user can send it twice. Only server confirmation may compact this.
it("never evicts an unconfirmed entry, however many pile up", () => {
const store = createChatStore({ storage: memStorage() });
for (let i = 0; i < 60; i++) store.getState().markDraftRestoreApplied(`r-${i}`);
const ids = store.getState().appliedDraftRestoreIds;
expect(ids).toHaveLength(60);
expect(ids[0]).toBe("r-0");
expect(ids[59]).toBe("r-59");
// The one exit: the server confirmed the row is gone.
store.getState().forgetDraftRestoreApplied("r-0");
expect(store.getState().appliedDraftRestoreIds).toHaveLength(59);
expect(store.getState().appliedDraftRestoreIds[0]).toBe("r-1");
});
});
// Coordinator-owned upload lifecycle in the draft slots (MUL-5181 L2).
describe("chat store — draft upload ops", () => {
const ATTACHMENTS_KEY = "multica:chat:draft-attachments";
function freshStore() {
const storage = memStorage();
return { storage, store: createChatStore({ storage }) };
}
it("add → settle keeps the clientUploadId and strips the signed download_url", () => {
const { storage, store } = freshStore();
const s = store.getState();
s.addInputDraftUpload("session-1", {
clientUploadId: "c1",
status: "uploading",
filename: "shot.png",
size: 9,
});
expect(store.getState().inputDraftAttachments["session-1"]?.[0]?.status).toBe("uploading");
s.settleInputDraftUpload("session-1", "c1", {
...makeAttachment("att-1"),
download_url: "/uploads/att-1.png?Signature=short-lived",
});
const settled = store.getState().inputDraftAttachments["session-1"]?.[0];
expect(settled).toMatchObject({ clientUploadId: "c1", status: "uploaded" });
expect(settled?.status === "uploaded" && settled.attachment.id).toBe("att-1");
// Drafts survive restarts; a response-scoped signed URL must not.
expect(settled?.status === "uploaded" && settled.attachment.download_url).toBe("");
// And the persisted blob agrees with memory.
expect(storage.getItem(ATTACHMENTS_KEY)).toContain('"c1"');
expect(storage.getItem(ATTACHMENTS_KEY)).not.toContain("Signature=");
});
it("addInputDraftUpload dedupes by clientUploadId", () => {
const { store } = freshStore();
const s = store.getState();
const placeholder = {
clientUploadId: "c1",
status: "uploading" as const,
filename: "a.png",
size: 1,
};
s.addInputDraftUpload("session-1", placeholder);
s.addInputDraftUpload("session-1", placeholder);
expect(store.getState().inputDraftAttachments["session-1"]).toHaveLength(1);
});
it("failInputDraftUpload marks the placeholder failed with its reason", () => {
const { store } = freshStore();
const s = store.getState();
s.addInputDraftUpload("session-1", {
clientUploadId: "c1",
status: "uploading",
filename: "a.png",
size: 1,
});
s.failInputDraftUpload("session-1", "c1", "network down");
expect(store.getState().inputDraftAttachments["session-1"]?.[0]).toMatchObject({
status: "failed",
error: "network down",
filename: "a.png",
});
});
it("removeInputDraftUpload drops the entry and prunes an empty slot", () => {
const { storage, store } = freshStore();
const s = store.getState();
s.addInputDraftUpload("session-1", {
clientUploadId: "c1",
status: "uploading",
filename: "a.png",
size: 1,
});
s.removeInputDraftUpload("session-1", "c1");
expect(store.getState().inputDraftAttachments["session-1"]).toBeUndefined();
expect(storage.getItem(ATTACHMENTS_KEY)).toBeNull();
});
it("appendToInputDraft lands after trimmed text, or bare on an empty slot", () => {
const { store } = freshStore();
const s = store.getState();
s.setInputDraft("session-1", "wip text \n");
s.appendToInputDraft("session-1", "![shot.png](/api/attachments/att-1/download)");
expect(store.getState().inputDrafts["session-1"]).toBe(
"wip text\n\n![shot.png](/api/attachments/att-1/download)",
);
s.appendToInputDraft("session-2", "[doc.pdf](/api/attachments/att-2/download)");
expect(store.getState().inputDrafts["session-2"]).toBe(
"[doc.pdf](/api/attachments/att-2/download)",
);
});
});