Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): retain create fields within a batch (MUL-7648) (#8783)
hutiefang7687acc1d86227
diff --git a/packages/core/issues/stores/draft-store.test.ts b/packages/core/issues/stores/draft-store.test.tsindex 9b62ee3564..cb619a1181 100644--- a/packages/core/issues/stores/draft-store.test.ts+++ b/packages/core/issues/stores/draft-store.test.ts@@ -54,6 +54,7 @@ const RESET_STATE = {},lastAssigneeType: undefined,lastAssigneeId: undefined,+ batchContinuationBaseline: undefined,};describe("issue draft store — last assignee", () => {@@ -75,6 +76,73 @@ describe("issue draft store — last assignee", () => {expect(draft.manual.assigneeId).toBe("alice");});+ it("clearDraft resets status for a fresh create", () => {+ const { setManual, clearDraft } = useIssueDraftStore.getState();+ setManual({ status: "done" });+ clearDraft();++ expect(useIssueDraftStore.getState().draft.manual.status).toBe("todo");+ });++ it("persists todo for an untouched batch continuation but keeps an explicitly edited draft", async () => {+ setCurrentWorkspace("batch", "ws_batch");+ await flush();+ await flush();++ const storedStatus = () =>+ JSON.parse(localStorage.getItem("multica_issue_draft:batch") ?? "{}").state.draft.manual.status;++ const store = useIssueDraftStore.getState();+ // "Create another" resets the form but carries the submitted status and+ // assignee into the next issue, so the reset itself is not user input.+ store.setManual({ status: "in_progress", assigneeType: "member", assigneeId: "alice" });+ store.beginBatchContinuation();+ expect(storedStatus()).toBe("todo");++ // A field the user changed IS input, even before a title is typed.+ useIssueDraftStore.getState().setManual({ status: "done" });+ expect(storedStatus()).toBe("done");++ // As is a started next issue.+ useIssueDraftStore.getState().setManual({ title: "Unfinished next issue" });+ expect(storedStatus()).toBe("done");+ setCurrentWorkspace(null, null);+ });++ it("persists an explicitly selected status on a fresh create before any title is typed", async () => {+ setCurrentWorkspace("status-only", "ws_status");+ await flush();+ await flush();++ useIssueDraftStore.getState().setManual({ status: "in_progress" });++ const stored = JSON.parse(localStorage.getItem("multica_issue_draft:status-only") ?? "{}");+ expect(stored.state.draft.manual.status).toBe("in_progress");+ setCurrentWorkspace(null, null);+ });++ it("rehydrates an explicitly selected status that never got a title", async () => {+ setCurrentWorkspace("status-rehydrate", "ws_status");+ await flush();+ await flush();++ useIssueDraftStore.getState().setManual({ status: "in_progress" });+ expect(+ JSON.parse(localStorage.getItem("multica_issue_draft:status-rehydrate") ?? "{}")+ .state.draft.manual.status,+ ).toBe("in_progress");++ // Leave and come back to the workspace: the persisted selection returns.+ setCurrentWorkspace(null, null);+ await flush();+ setCurrentWorkspace("status-rehydrate", "ws_status");+ await flush();+ await flush();++ expect(useIssueDraftStore.getState().draft.manual.status).toBe("in_progress");+ setCurrentWorkspace(null, null);+ });+it("clearDraft yields an empty assignee when none has ever been remembered", () => {const { setManual, clearDraft } = useIssueDraftStore.getState();@@ -178,6 +246,215 @@ describe("issue draft store — last assignee", () => {});});+describe("issue draft store — keep-open batch continuation", () => {+ beforeEach(() => {+ useIssueDraftStore.setState(RESET_STATE);+ });++ // Stands in for `resetForNextIssue` in the create dialog: the batch reset+ // writes the carried values, then marks the result as the baseline.+ function beginContinuation() {+ const store = useIssueDraftStore.getState();+ store.setManual({ status: "in_progress", assigneeType: "member", assigneeId: "alice" });+ store.beginBatchContinuation();+ }++ it("does not treat an untouched continuation's inherited fields as a draft", () => {+ beginContinuation();++ expect(useIssueDraftStore.getState().hasDraft()).toBe(false);+ });++ it.each([+ ["priority", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setShared({ priority: "high" })],+ ["project", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setShared({ projectId: "project-1" })],+ ["due date", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setShared({ dueDate: "2026-10-01" })],+ ["start date", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ startDate: "2026-10-01" })],+ ["labels", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ labelIds: ["label-1"] })],+ ["status", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ status: "done" })],+ ["assignee", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ assigneeId: "bob" })],+ ["custom properties", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ propertyValues: { "property-1": "option-1" } })],+ ["title", (s: ReturnType<typeof useIssueDraftStore.getState>) => s.setManual({ title: "Next issue" })],+ ])("keeps a %s-only edit recoverable after a keep-open reset", (_field, edit) => {+ beginContinuation();+ expect(useIssueDraftStore.getState().hasDraft()).toBe(false);++ edit(useIssueDraftStore.getState());++ expect(useIssueDraftStore.getState().hasDraft()).toBe(true);+ });++ it("does not treat a mode switch on an untouched continuation as an edit", () => {+ beginContinuation();++ // `switchToAgent` commits the manual form's shared fields, flips the active+ // mode and (on a blank form) leaves the agent slot empty. None of that is+ // user intent, so the continuation is still untouched.+ const store = useIssueDraftStore.getState();+ store.setShared({ projectId: undefined, priority: "none", dueDate: null });+ store.setActiveMode("agent");++ expect(useIssueDraftStore.getState().hasDraft()).toBe(false);+ });++ it("persists todo for a continuation that was only switched to agent mode", async () => {+ setCurrentWorkspace("mode-switch", "ws_mode");+ await flush();+ await flush();++ const storedStatus = () =>+ JSON.parse(localStorage.getItem("multica_issue_draft:mode-switch") ?? "{}").state.draft.manual.status;++ beginContinuation();+ expect(storedStatus()).toBe("todo");++ const store = useIssueDraftStore.getState();+ store.setShared({ projectId: undefined, priority: "none", dueDate: null });+ store.setActiveMode("agent");++ // A mode switch is not an edit: the batch's status must not survive into+ // the next fresh create through storage either.+ expect(storedStatus()).toBe("todo");+ setCurrentWorkspace(null, null);+ });++ it("does not treat a mode switch's agent assist-init as an edit", () => {+ const store = useIssueDraftStore.getState();+ // A batch that inherited an agent assignee: `switchToAgent` hands it to the+ // agent slot so the next issue can be filed by the same agent.+ store.setManual({ status: "in_progress", assigneeType: "agent", assigneeId: "agent-1" });+ useIssueDraftStore.getState().beginBatchContinuation();++ const switching = useIssueDraftStore.getState();+ switching.setShared({ projectId: undefined, priority: "none", dueDate: null });+ switching.setAgent({ actorType: "agent", actorId: "agent-1" });+ switching.setActiveMode("agent");++ // The agent slot belongs to the other form, so filling it is not an edit of+ // the continuation the manual form left behind.+ expect(useIssueDraftStore.getState().hasDraft()).toBe(false);+ });++ it("keeps an edited draft and its status recoverable across a mode switch", async () => {+ setCurrentWorkspace("switch-edit", "ws_switch");+ await flush();+ await flush();++ const storedDraft = () =>+ JSON.parse(localStorage.getItem("multica_issue_draft:switch-edit") ?? "{}").state.draft ?? {};++ beginContinuation();+ // A real selection for the next issue, re-committed by the switch along+ // with the mode flip.+ const store = useIssueDraftStore.getState();+ store.setShared({ priority: "high" });+ store.setShared({ projectId: undefined, priority: "high", dueDate: null });+ store.setActiveMode("agent");++ expect(useIssueDraftStore.getState().hasDraft()).toBe(true);+ expect(storedDraft().shared?.priority).toBe("high");+ expect(storedDraft().manual?.status).toBe("in_progress");+ setCurrentWorkspace(null, null);+ });++ it("ends an untouched continuation by normalizing only its inherited status", () => {+ beginContinuation();+ useIssueDraftStore.getState().endBatchContinuation();++ const state = useIssueDraftStore.getState();+ expect(state.draft.manual.status).toBe("todo");+ // Closing is not a fresh create: the rest of the reset — the carried+ // assignee, the shared slot — is left exactly as it was.+ expect(state.draft.manual.assigneeId).toBe("alice");+ expect(state.draft.shared.priority).toBe("none");+ expect(state.batchContinuationBaseline).toBeUndefined();+ });++ it("keeps an edited continuation as it is, inherited status included", () => {+ beginContinuation();+ const store = useIssueDraftStore.getState();+ store.setShared({ priority: "high" });+ store.setAgent({ prompt: "audit the flaky test" });++ useIssueDraftStore.getState().endBatchContinuation();++ const state = useIssueDraftStore.getState();+ expect(state.draft.shared.priority).toBe("high");+ // Agent-side content is a real draft, not continuation bookkeeping.+ expect(state.draft.agent.prompt).toBe("audit the flaky test");+ // An edited continuation is the user's unfinished next issue, so the+ // status the batch inherited stays with it.+ expect(state.draft.manual.status).toBe("in_progress");+ expect(state.batchContinuationBaseline).toBeUndefined();+ });++ it("keeps a status the user picked in the continuation", () => {+ beginContinuation();+ useIssueDraftStore.getState().setManual({ status: "done" });++ useIssueDraftStore.getState().endBatchContinuation();++ expect(useIssueDraftStore.getState().draft.manual.status).toBe("done");+ });++ it("normalizes a mode-only continuation's status and keeps its seeded agent prompt", () => {+ const store = useIssueDraftStore.getState();+ store.setManual({ status: "in_progress", assigneeType: "agent", assigneeId: "agent-1" });+ useIssueDraftStore.getState().beginBatchContinuation();++ // `switchToAgent` commits the unchanged shared fields, seeds the agent slot+ // from the manual form and flips the mode — none of it a manual edit.+ const switching = useIssueDraftStore.getState();+ switching.setShared({ projectId: undefined, priority: "none", dueDate: null });+ switching.setAgent({ prompt: "audit the flaky test", actorType: "agent", actorId: "agent-1" });+ switching.setActiveMode("agent");++ useIssueDraftStore.getState().endBatchContinuation();++ const state = useIssueDraftStore.getState();+ // Only the inherited status is dropped; the agent side is left intact.+ expect(state.draft.manual.status).toBe("todo");+ expect(state.draft.agent.prompt).toBe("audit the flaky test");+ expect(state.draft.agent.actorId).toBe("agent-1");+ expect(state.draft.activeMode).toBe("agent");+ expect(state.batchContinuationBaseline).toBeUndefined();+ });++ it("leaves the restored ordinary draft alone when the snapshot is already gone", () => {+ // The source-context wrapper restores the ordinary draft and drops the+ // snapshot before the manual panel's close cleanup runs.+ useIssueDraftStore.getState().setShared({ priority: "high" });+ useIssueDraftStore.getState().setManual({ status: "backlog" });+ const ordinary = useIssueDraftStore.getState().draft;++ useIssueDraftStore.getState().endBatchContinuation();++ expect(useIssueDraftStore.getState().draft).toBe(ordinary);+ });++ it("stops tracking a continuation once the draft is cleared", () => {+ beginContinuation();+ useIssueDraftStore.getState().clearDraft();+ expect(useIssueDraftStore.getState().batchContinuationBaseline).toBeUndefined();++ // The fresh draft is judged on content alone again — and its status is the+ // reset todo, not whatever the batch had submitted.+ useIssueDraftStore.getState().setManual({ status: "in_progress" });+ expect(useIssueDraftStore.getState().draft.manual.status).toBe("in_progress");+ expect(useIssueDraftStore.getState().hasDraft()).toBe(false);+ });++ it("drops the continuation snapshot when an isolated draft session starts", () => {+ beginContinuation();+ const isolated = useIssueDraftStore.getState();+ isolated.beginIsolatedDraft();+ expect(useIssueDraftStore.getState().batchContinuationBaseline).toBeUndefined();++ useIssueDraftStore.getState().endIsolatedDraft();+ expect(useIssueDraftStore.getState().batchContinuationBaseline).toBeUndefined();+ });+});+describe("issue draft store — mode switch preserves both sides", () => {beforeEach(() => {useIssueDraftStore.setState(RESET_STATE);@@ -212,6 +489,35 @@ describe("issue draft store — legacy rehydrate", () => {setCurrentWorkspace(null, null);});+ it("drops obsolete status and stage preferences from persisted state", async () => {+ localStorage.setItem(+ "multica_issue_draft:legacy-pref",+ JSON.stringify({+ state: {+ draft: { manual: { status: "todo" } },+ lastStatus: "done",+ lastStage: 3,+ lastStageParentIssueId: "parent-a",+ },+ version: 0,+ }),+ );++ setCurrentWorkspace("legacy-pref", "ws_pref");+ await flush();+ await flush();++ const state = useIssueDraftStore.getState();+ expect("lastStatus" in state).toBe(false);+ expect("lastStage" in state).toBe(false);+ expect("lastStageParentIssueId" in state).toBe(false);+ state.setManual({ title: "new draft" });+ const stored = JSON.parse(localStorage.getItem("multica_issue_draft:legacy-pref") ?? "{}");+ expect(stored.state).not.toHaveProperty("lastStatus");+ expect(stored.state).not.toHaveProperty("lastStage");+ expect(stored.state).not.toHaveProperty("lastStageParentIssueId");+ });+it("migrates a pre-MUL-5181 flat draft into the shared/manual slots", async () => {localStorage.setItem("multica_issue_draft:acme",diff --git a/packages/core/issues/stores/draft-store.ts b/packages/core/issues/stores/draft-store.tsindex f472324087..87662e1e12 100644--- a/packages/core/issues/stores/draft-store.ts+++ b/packages/core/issues/stores/draft-store.ts@@ -101,6 +101,14 @@ interface IssueDraftStore {* create session and persistence continues to serialize this ordinary* backup, so a reload cannot leak the source draft into normal create. */isolatedDraftBackup?: IssueCreateDraft;+ /** In-memory only. Snapshot of the draft a successful "Create another"+ * create reset into the next issue of the batch. Compared by value over the+ * manual form's fields, so an untouched continuation — which merely+ * inherits the submitted status/assignee, and may be rewritten by a mode+ * switch — is not recoverable content, while any field the user actually+ * changed is. Never persisted: untouched continuations reload as todo;+ * genuinely edited drafts retain their selections. */+ batchContinuationBaseline?: IssueCreateDraft;// Last assignee picked at submit time. Persisted across drafts so the// create-issue modal can prefill the picker with the user's most recent// choice instead of always opening with no assignee.@@ -110,6 +118,16 @@ interface IssueDraftStore {setManual: (patch: Partial<IssueCreateManual>) => void;setAgent: (patch: Partial<IssueCreateAgent>) => void;setActiveMode: (mode: CreateMode) => void;+ /** Record the current draft as the untouched baseline of a keep-open batch+ * continuation. Call once a successful create has reset the draft for the+ * next issue; holding the reference is safe because every write below+ * rebuilds `draft` instead of mutating it. Cleared whenever the draft+ * stops being that continuation (fresh draft, isolated session, rehydrate). */+ beginBatchContinuation: () => void;+ /** Normalize an untouched continuation on close, preserving real edits and+ * agent data. No-op after a source-context close restores the ordinary draft+ * and clears the continuation snapshot. */+ endBatchContinuation: () => void;clearDraft: () => void;beginIsolatedDraft: () => void;endIsolatedDraft: () => void;@@ -178,6 +196,78 @@ function migrateDraft(raw: unknown): IssueCreateDraft {};}+function hasDraftContent(draft: IssueCreateDraft): boolean {+ const { manual, agent, shared } = draft;+ return !!(+ manual.title ||+ manual.description ||+ agent.prompt ||+ Object.keys(manual.propertyValues).length > 0 ||+ // Recoverable uploads only; failed/interrupted remnants do not pin a draft.+ shared.attachments.some((u) => u.status === "uploaded" || u.status === "uploading")+ );+}++// Value equality over the draft's plain-object shape. An untouched draft is+// usually still the same reference; the structural walk additionally absorbs a+// re-created draft whose values did not change, so an internal rewrite can+// never read as an edit. Only compares shapes this store writes — nested+// arrays (labelIds, attachments) and plain records (propertyValues).+function draftValuesEqual(a: unknown, b: unknown): boolean {+ if (Object.is(a, b)) return true;+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;+ if (Array.isArray(a) || Array.isArray(b)) {+ return (+ Array.isArray(a) &&+ Array.isArray(b) &&+ a.length === b.length &&+ a.every((item, i) => draftValuesEqual(item, b[i]))+ );+ }+ const left = a as Record<string, unknown>;+ const right = b as Record<string, unknown>;+ for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) {+ if (!draftValuesEqual(left[key], right[key])) return false;+ }+ return true;+}++// Mode switches may seed the agent slot without editing the manual form.+// Compare only shared/manual values when deciding whether that form changed.+function manualFormChanged(draft: IssueCreateDraft, baseline: IssueCreateDraft): boolean {+ return !draftValuesEqual(+ { shared: draft.shared, manual: draft.manual },+ { shared: baseline.shared, manual: baseline.manual },+ );+}++// Only untouched manual continuations have an inherited status to normalize.+function hasInheritedStatus(+ draft: IssueCreateDraft,+ batchContinuationBaseline?: IssueCreateDraft,+): boolean {+ return (+ batchContinuationBaseline !== undefined &&+ !manualFormChanged(draft, batchContinuationBaseline)+ );+}++// Whether the draft holds anything worth recovering: explicit content, or a+// change away from the untouched keep-open continuation it started from. A+// batch continuation inherits the submitted status and assignee, so those+// inherited values only count once the user changes them — otherwise an+// unedited continuation would keep the inherited status alive (and persist it).+function hasRecoverableIntent(+ draft: IssueCreateDraft,+ batchContinuationBaseline?: IssueCreateDraft,+): boolean {+ return (+ hasDraftContent(draft) ||+ (batchContinuationBaseline !== undefined &&+ manualFormChanged(draft, batchContinuationBaseline))+ );+}+export const useIssueDraftStore = create<IssueDraftStore>()(persist((set, get) => ({@@ -192,6 +282,21 @@ export const useIssueDraftStore = create<IssueDraftStore>()(set((s) => ({ draft: { ...s.draft, agent: { ...s.draft.agent, ...patch } } })),setActiveMode: (mode) =>set((s) => ({ draft: { ...s.draft, activeMode: mode } })),+ beginBatchContinuation: () =>+ set((s) => ({ batchContinuationBaseline: s.draft })),+ endBatchContinuation: () =>+ set((s) => {+ const baseline = s.batchContinuationBaseline;+ // Outer layout cleanup may already have restored the ordinary draft.+ if (!baseline) return s;+ // Genuine manual edits remain an unfinished draft, including status.+ return {+ draft: hasInheritedStatus(s.draft, baseline)+ ? { ...s.draft, manual: { ...s.draft.manual, status: "todo" } }+ : s.draft,+ batchContinuationBaseline: undefined,+ };+ }),clearDraft: () =>set((s) => ({draft: {@@ -204,12 +309,14 @@ export const useIssueDraftStore = create<IssueDraftStore>()(agent: emptyAgent(),activeMode: s.draft.activeMode,},+ batchContinuationBaseline: undefined,})),beginIsolatedDraft: () =>set((s) => {if (s.isolatedDraftBackup) return s;return {isolatedDraftBackup: s.draft,+ batchContinuationBaseline: undefined,draft: {shared: emptyShared(),manual: {@@ -224,21 +331,13 @@ export const useIssueDraftStore = create<IssueDraftStore>()(}),endIsolatedDraft: () =>set((s) => s.isolatedDraftBackup- ? { draft: s.isolatedDraftBackup, isolatedDraftBackup: undefined }+ ? { draft: s.isolatedDraftBackup, isolatedDraftBackup: undefined, batchContinuationBaseline: undefined }: s),setLastAssignee: (type, id) =>set({ lastAssigneeType: type, lastAssigneeId: id }),hasDraft: () => {- const { manual, agent, shared } = get().draft;- return !!(- manual.title ||- manual.description ||- agent.prompt ||- Object.keys(manual.propertyValues).length > 0 ||- // Recoverable uploads only: a failed/interrupted remnant the user- // never dismissed must not pin the sidebar's draft dot forever.- shared.attachments.some((u) => u.status === "uploaded" || u.status === "uploading")- );+ const { draft, batchContinuationBaseline } = get();+ return hasRecoverableIntent(draft, batchContinuationBaseline);},}),{@@ -247,19 +346,33 @@ export const useIssueDraftStore = create<IssueDraftStore>()(// An isolated source-context draft must never reach localStorage. Persist// the ordinary backup throughout that session; a crash/reload therefore// restores the user's normal create draft, not source-specific input.- partialize: (state) => ({- draft: state.isolatedDraftBackup ?? state.draft,- lastAssigneeType: state.lastAssigneeType,- lastAssigneeId: state.lastAssigneeId,- }),+ partialize: (state) => {+ const draft = state.isolatedDraftBackup ?? state.draft;+ // Normalize only untouched continuations; preserve edited drafts and+ // the ordinary backup throughout an isolated source-context session.+ const inheritedStatus =+ state.isolatedDraftBackup === undefined &&+ hasInheritedStatus(state.draft, state.batchContinuationBaseline);+ return {+ draft: inheritedStatus+ ? { ...draft, manual: { ...draft.manual, status: "todo" as const } }+ : draft,+ lastAssigneeType: state.lastAssigneeType,+ lastAssigneeId: state.lastAssigneeId,+ };+ },merge: (persistedState, currentState) => {const persisted = (persistedState ?? {}) as Partial<IssueDraftStore> & {draft?: unknown;};return {...currentState,- ...persisted,+ lastAssigneeType: persisted.lastAssigneeType,+ lastAssigneeId: persisted.lastAssigneeId,draft: migrateDraft(persisted.draft),+ // A rehydrate replaces the draft (fresh load or workspace switch), so+ // the in-memory continuation snapshot no longer describes it.+ batchContinuationBaseline: undefined,};},},@@ -281,5 +394,6 @@ registerDraftCleanup({lastAssigneeType: undefined,lastAssigneeId: undefined,isolatedDraftBackup: undefined,+ batchContinuationBaseline: undefined,}),});diff --git a/packages/views/modals/create-issue-batch-continuation.test.tsx b/packages/views/modals/create-issue-batch-continuation.test.tsxnew file mode 100644index 0000000000..cf10860252--- /dev/null+++ b/packages/views/modals/create-issue-batch-continuation.test.tsx@@ -0,0 +1,600 @@+// @vitest-environment jsdom+// Store-backed lifecycle tests cover mode switches and parent-before-child+// layout cleanup without mocking the draft store.+import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../locales/en/common.json";+import enModals from "../locales/en/modals.json";+import enEditor from "../locales/en/editor.json";+import enIssues from "../locales/en/issues.json";++const TEST_RESOURCES = {+ en: { common: enCommon, modals: enModals, editor: enEditor, issues: enIssues },+};++const { SOURCE_CONTEXT_PREVIEW } = vi.hoisted(() => ({ SOURCE_CONTEXT_PREVIEW: {+ source_issue: {+ id: "issue-source",+ identifier: "MUL-9",+ number: 9,+ title: "Source",+ description: "Historical body",+ created_at: "2026-08-20T00:00:00Z",+ updated_at: "2026-08-21T00:00:00Z",+ revision: 1,+ attachments: [],+ },+ comment_thread: [{+ id: "comment-source",+ parent_id: null,+ type: "comment",+ content: "Historical comment",+ author: { type: "member", id: "user-1", name: "Alice" },+ created_at: "2026-08-21T00:00:00Z",+ updated_at: "2026-08-21T00:00:00Z",+ revision: 1,+ attachments: [],+ }],+ anchor_comment_id: "comment-source",+ capture_token: "sha256:preview-token",+ limits: {+ comment_count: 1,+ text_bytes: 100,+ attachment_count: 0,+ attachment_bytes: 0,+ },+} }));++const mockCreateIssue = vi.hoisted(() => vi.fn());+const mockCreateCommentSubIssue = vi.hoisted(() => vi.fn());+const mockListProperties = vi.hoisted(() => vi.fn());++// A single `ApiError` identity for the component's cross-realm `instanceof`+// check; the schema helpers stay real so the drift-fallback branch runs the+// actual validation logic.+const { ApiError } = vi.hoisted(() => {+ class ApiErrorImpl extends Error {+ readonly status: number;+ readonly statusText: string;+ readonly body?: unknown;+ constructor(message: string, status: number, statusText: string, body?: unknown) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ this.statusText = statusText;+ this.body = body;+ }+ }+ return { ApiError: ApiErrorImpl };+});++vi.mock("../navigation/context", () => ({+ useNavigation: () => ({ push: vi.fn() }),+}));++vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ name: "Test Workspace" }),+ useWorkspacePaths: () => ({+ issueDetail: (id: string) => `/ws-test/issues/${id}`,+ settings: () => "/ws-test/settings",+ }),+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-test",+}));++vi.mock("./use-issue-limit-upgrade-prompt", () => ({+ useIssueLimitUpgradePrompt: () => vi.fn(),+}));++vi.mock("@multica/core/issues/queries", () => ({+ issueDetailOptions: (wsId: string, id: string) => ({+ queryKey: ["issues", wsId, "detail", id],+ queryFn: () => Promise.resolve(null),+ }),+ childIssuesOptions: (wsId: string, id: string) => ({+ queryKey: ["issues", wsId, "children", id],+ queryFn: () => Promise.resolve([]),+ }),+ sourceContextPreviewOptions: (wsId: string, anchorCommentId: string) => ({+ queryKey: ["issues", wsId, "source-context", anchorCommentId],+ queryFn: () => Promise.resolve(SOURCE_CONTEXT_PREVIEW),+ }),+}));++vi.mock("../issues/hooks/use-issue-trigger-preview", () => ({+ useIssueTriggerPreview: () => ({ triggers: [], totalCount: 0, isLoading: false }),+}));++vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Agent" }),+}));++vi.mock("../common/actor-avatar", () => ({+ ActorAvatar: () => null,+}));++vi.mock("@multica/core/issues/mutations", () => ({+ useCreateIssue: () => ({ mutateAsync: mockCreateIssue }),+ useCreateCommentSubIssue: () => ({+ mutateAsync: ({ anchorCommentId, data }: { anchorCommentId: string; data: unknown }) =>+ mockCreateCommentSubIssue(anchorCommentId, data),+ }),+ useUpdateIssue: () => ({ mutate: vi.fn() }),+}));++vi.mock("@multica/core/labels", () => ({+ useAttachLabelToIssue: () => ({ mutateAsync: vi.fn() }),+}));++vi.mock("@multica/core/properties", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@multica/core/properties")>();+ return {+ ...actual,+ useSetIssueProperty: () => ({ mutateAsync: vi.fn() }),+ };+});++vi.mock("@multica/core/api", async () => {+ const { parseWithFallback } = await vi.importActual<typeof import("@multica/core/api/schema")>(+ "@multica/core/api/schema",+ );+ const { DuplicateIssueErrorBodySchema } = await vi.importActual<+ typeof import("@multica/core/api/schemas")+ >("@multica/core/api/schemas");+ return {+ api: {+ listProperties: mockListProperties,+ uploadFile: vi.fn(),+ },+ ApiError,+ parseWithFallback,+ DuplicateIssueErrorBodySchema,+ };+});++vi.mock("../editor", async () => {+ const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>(+ "../editor/use-upload-gate",+ );+ const composer = await vi.importActual<typeof import("../editor/use-composer-submit")>(+ "../editor/use-composer-submit",+ );++ const ContentEditor = forwardRef(({ defaultValue, onUpdate, placeholder }: any, ref: any) => {+ const valueRef = useRef(defaultValue || "");+ const [value, setValue] = useState(defaultValue || "");+ // Mirrors the real editor's debounce: `flushPendingUpdate` reports a value+ // only when an update is still unflushed, and `null`/`undefined` otherwise+ // (the create flow treats "nothing pending" as "no edit to re-snapshot").+ const pendingRef = useRef(false);+ useImperativeHandle(ref, () => ({+ getMarkdown: () => valueRef.current,+ flushPendingUpdate: () => {+ if (!pendingRef.current) return undefined;+ pendingRef.current = false;+ return valueRef.current;+ },+ clearContent: () => {+ pendingRef.current = false;+ valueRef.current = "";+ setValue("");+ },+ hasActiveUploads: () => false,+ insertUploadPlaceholder: () => true,+ settleUploadPlaceholder: () => false,+ }));+ return (+ <textarea+ value={value}+ placeholder={placeholder}+ onChange={(e) => {+ pendingRef.current = true;+ valueRef.current = e.target.value;+ setValue(e.target.value);+ onUpdate?.(e.target.value);+ }}+ />+ );+ });+ ContentEditor.displayName = "ContentEditor";++ const TitleEditor = forwardRef(+ ({ defaultValue, placeholder, onChange, onSubmit }: any, ref: any) => {+ const valueRef = useRef(defaultValue || "");+ const [value, setValue] = useState(defaultValue || "");+ const inputRef = useRef<HTMLInputElement>(null);+ useImperativeHandle(ref, () => ({+ getText: () => valueRef.current,+ focus: () => inputRef.current?.focus(),+ focusAtCoords: () => inputRef.current?.focus(),+ }));+ return (+ <input+ ref={inputRef}+ value={value}+ placeholder={placeholder}+ onChange={(e) => {+ valueRef.current = e.target.value;+ setValue(e.target.value);+ onChange?.(e.target.value);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") onSubmit?.();+ }}+ />+ );+ },+ );+ TitleEditor.displayName = "TitleEditor";++ return {+ ...uploadGate,+ ...composer,+ useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),+ FileDropOverlay: () => null,+ ContentEditor,+ TitleEditor,+ };+});++vi.mock("../issues/components", () => ({+ StatusIcon: ({ status }: { status: string }) => <span data-testid="status-icon">{status}</span>,+ // Drives the two field-level edits a batch continuation must tell apart from+ // the inherited values it started with.+ StatusPicker: ({ onUpdate }: { onUpdate: (u: { status: string }) => void }) => (+ <button type="button" data-testid="status-picker" onClick={() => onUpdate({ status: "done" })} />+ ),+ PriorityPicker: ({ onUpdate }: { onUpdate: (u: { priority: string }) => void }) => (+ <button type="button" data-testid="priority-picker" onClick={() => onUpdate({ priority: "high" })} />+ ),+ StagePicker: () => <div data-testid="stage-picker" />,+ AssigneePicker: () => <div data-testid="assignee-picker" />,+ StartDatePicker: () => <div data-testid="start-date-picker" />,+ DueDatePicker: () => <div data-testid="due-date-picker" />,+ LabelPicker: () => <div data-testid="label-picker" />,+}));++vi.mock("../projects/components/project-picker", () => ({+ ProjectPicker: () => <div data-testid="project-picker" />,+}));++vi.mock("@multica/ui/components/ui/dialog", () => ({+ Dialog: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DialogContent: ({ children, className }: { children: ReactNode; className?: string }) => (+ <div className={className}>{children}</div>+ ),+ DialogTitle: ({ children, className }: { children: ReactNode; className?: string }) => (+ <div className={className}>{children}</div>+ ),+}));++vi.mock("@multica/ui/components/ui/dropdown-menu", () => {+ const Pass = ({ children }: { children: ReactNode }) => <>{children}</>;+ return {+ DropdownMenu: Pass,+ DropdownMenuTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,+ DropdownMenuContent: Pass,+ DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (+ <button type="button" onClick={onClick}>{children}</button>+ ),+ DropdownMenuSeparator: () => null,+ DropdownMenuSub: Pass,+ DropdownMenuSubTrigger: Pass,+ DropdownMenuSubContent: Pass,+ };+});++vi.mock("@multica/ui/components/ui/tooltip", () => {+ const Pass = ({ children }: { children: ReactNode }) => <>{children}</>;+ return {+ Tooltip: Pass,+ TooltipTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,+ TooltipContent: Pass,+ TooltipProvider: Pass,+ };+});++vi.mock("@multica/ui/components/ui/button", () => ({+ Button: ({+ children,+ disabled,+ onClick,+ type = "button",+ ...rest+ }: {+ children: ReactNode;+ disabled?: boolean;+ onClick?: () => void;+ type?: "button" | "submit" | "reset";+ [key: string]: unknown;+ }) => (+ <button type={type} disabled={disabled} onClick={onClick} {...rest}>+ {children}+ </button>+ ),+}));++vi.mock("@multica/ui/components/ui/switch", () => ({+ Switch: ({+ checked,+ onCheckedChange,+ }: {+ checked: boolean;+ onCheckedChange: (v: boolean) => void;+ }) => (+ <input+ aria-label="Create another"+ type="checkbox"+ checked={checked}+ onChange={(e) => onCheckedChange(e.target.checked)}+ />+ ),+}));++vi.mock("@multica/ui/components/common/file-upload-button", () => ({+ FileUploadButton: () => null,+}));++vi.mock("@multica/ui/lib/utils", () => ({+ cn: (...values: Array<string | false | null | undefined>) => values.filter(Boolean).join(" "),+}));++vi.mock("sonner", () => ({+ toast: { custom: vi.fn(), dismiss: vi.fn(), error: vi.fn() },+}));++vi.mock("./issue-picker-modal", () => ({+ IssuePickerModal: () => null,+}));++import { ManualCreatePanel } from "./create-issue";+import { CreateIssueDialog } from "./create-issue-dialog";+// The REAL stores: this suite exists to exercise the real cleanup predicate and+// the real persistence around it.+import {+ useIssueDraftStore,+ type IssueCreateDraft,+} from "@multica/core/issues/stores/draft-store";+import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-store";++const emptyDraft = (): IssueCreateDraft => ({+ shared: { projectId: undefined, priority: "none", dueDate: null, attachments: [] },+ manual: {+ title: "",+ description: "",+ status: "todo",+ startDate: null,+ assigneeType: undefined,+ assigneeId: undefined,+ labelIds: [],+ propertyValues: {},+ },+ agent: { prompt: "", actorType: undefined, actorId: undefined },+ activeMode: "manual",+});++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++function renderUi(element: React.ReactElement) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <I18nWrapper>+ <QueryClientProvider client={qc}>{element}</QueryClientProvider>+ </I18nWrapper>,+ );+}++const draftState = () => useIssueDraftStore.getState();++beforeEach(() => {+ vi.clearAllMocks();+ useIssueDraftStore.setState({+ draft: emptyDraft(),+ isolatedDraftBackup: undefined,+ batchContinuationBaseline: undefined,+ lastAssigneeType: undefined,+ lastAssigneeId: undefined,+ });+ useQuickCreateStore.setState({ keepOpen: false });+ mockListProperties.mockResolvedValue({ properties: [] });+ const createdIssue = {+ id: "issue-1",+ identifier: "MUL-1",+ title: "Created",+ status: "todo",+ labels: [],+ };+ mockCreateIssue.mockResolvedValue(createdIssue);+ mockCreateCommentSubIssue.mockResolvedValue(createdIssue);+});++/**+ * Stands in for the create-issue shell's local mode state+ * (create-issue-dialog.tsx owns the real one): flipping to agent unmounts this+ * panel exactly like the shell does, which is the lifecycle under test. The+ * shell's own mode/carry wiring is covered by create-issue-dialog.test.tsx.+ */+function ModeSwitchHarness({ data }: { data?: Record<string, unknown> | null }) {+ const [mode, setMode] = useState<"manual" | "agent">("manual");+ const [isExpanded, setIsExpanded] = useState(false);+ if (mode === "agent") return null;+ return (+ <ManualCreatePanel+ onClose={() => {}}+ onSwitchMode={() => setMode("agent")}+ data={data}+ isExpanded={isExpanded}+ setIsExpanded={setIsExpanded}+ />+ );+}++/** Keep the batch pattern for the next issue: submit once with keep-open on. */+async function submitAndKeepOpen(user: ReturnType<typeof userEvent.setup>) {+ await user.type(screen.getByPlaceholderText("Issue title"), "First batch issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() => expect(draftState().batchContinuationBaseline).toBeDefined());+ expect(screen.getByPlaceholderText("Issue title")).toHaveValue("");+}++describe("keep-open continuation cleanup", () => {+ it("closes a continuation that was only switched to agent mode as a fresh todo create", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });++ const modal = renderUi(<ModeSwitchHarness data={{ status: "in_progress" }} />);+ await submitAndKeepOpen(user);+ // The inherited status is what the next issue in the batch starts from.+ expect(draftState().draft.manual.status).toBe("in_progress");++ // Only a mode switch — no manual field was touched.+ await user.click(screen.getByRole("button", { name: "Switch to Agent" }));++ // The continuation is gone, so the batch status must not reach the next+ // fresh manual create.+ expect(draftState().draft.manual.status).toBe("todo");+ expect(draftState().batchContinuationBaseline).toBeUndefined();+ expect(draftState().hasDraft()).toBe(false);++ modal.unmount();++ renderUi(<ModeSwitchHarness />);+ await user.type(screen.getByPlaceholderText("Issue title"), "Fresh manual issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() =>+ expect(mockCreateIssue).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: "todo" }),+ ),+ );+ });++ it("keeps a priority-only edit as-is, inherited batch status included", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });++ const modal = renderUi(<ModeSwitchHarness data={{ status: "in_progress" }} />);+ await submitAndKeepOpen(user);++ // Priority is a manual-form field, so it is a real selection the user made+ // for the next issue — unlike the status the batch inherited.+ await user.click(screen.getByTestId("priority-picker"));+ expect(draftState().draft.shared.priority).toBe("high");++ modal.unmount();++ // A genuine edit closes as the user's unfinished draft, status included.+ expect(draftState().draft.shared.priority).toBe("high");+ expect(draftState().draft.manual.status).toBe("in_progress");+ });++ it("keeps a status the user explicitly selected in the continuation", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });++ const modal = renderUi(<ModeSwitchHarness data={{ status: "in_progress" }} />);+ await submitAndKeepOpen(user);++ await user.click(screen.getByTestId("status-picker"));++ modal.unmount();++ expect(draftState().draft.manual.status).toBe("done");+ });++ it("keeps a shared-field edit recoverable when the form switches to agent", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });++ const modal = renderUi(<ModeSwitchHarness data={{ status: "in_progress" }} />);+ await submitAndKeepOpen(user);++ // A real selection for the next issue, made before the switch and+ // re-committed by it.+ await user.click(screen.getByTestId("priority-picker"));+ await user.click(screen.getByRole("button", { name: "Switch to Agent" }));++ expect(draftState().draft.shared.priority).toBe("high");+ // The selection is the user's, so the continuation closes as it is.+ expect(draftState().draft.manual.status).toBe("in_progress");+ expect(draftState().batchContinuationBaseline).toBeUndefined();++ modal.unmount();+ expect(draftState().draft.shared.priority).toBe("high");+ });++ it("preserves the seeded agent prompt of a started continuation across a switch", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });++ const modal = renderUi(<ModeSwitchHarness data={{ status: "in_progress" }} />);+ await submitAndKeepOpen(user);++ // The next issue of the batch was started: a title is real content, and the+ // switch seeds the agent prompt from it.+ await user.type(screen.getByPlaceholderText("Issue title"), "Second batch issue");+ await user.click(screen.getByRole("button", { name: "Switch to Agent" }));++ const state = draftState();+ expect(state.draft.agent.prompt).toBe("Second batch issue");+ expect(state.draft.manual.title).toBe("Second batch issue");+ expect(state.draft.manual.status).toBe("in_progress");++ modal.unmount();+ expect(draftState().draft.manual.title).toBe("Second batch issue");+ expect(draftState().draft.agent.prompt).toBe("Second batch issue");+ });++ it("restores the ordinary draft when a source-context keep-open session closes", async () => {+ const user = userEvent.setup();+ useQuickCreateStore.setState({ keepOpen: true });+ // An ordinary field-only draft: priority + status, no title or body, so+ // nothing counts as draft content and the status is not a batch default.+ useIssueDraftStore.setState({+ draft: {+ ...emptyDraft(),+ shared: { ...emptyDraft().shared, priority: "high" },+ manual: { ...emptyDraft().manual, status: "backlog" },+ },+ });++ // The real shell, so the source-context wrapper's layout-effect cleanup runs+ // before the manual panel's on unmount.+ const modal = renderUi(+ <CreateIssueDialog+ onClose={() => {}}+ initialMode="manual"+ data={{ anchor_comment_id: "comment-source" }}+ />,+ );+ await screen.findByPlaceholderText("Issue title");+ await submitAndKeepOpen(user);++ modal.unmount();++ // The restored ordinary draft is not a batch continuation to discard.+ expect(draftState().isolatedDraftBackup).toBeUndefined();+ expect(draftState().draft.shared.priority).toBe("high");+ expect(draftState().draft.manual.status).toBe("backlog");++ renderUi(<ModeSwitchHarness />);+ await user.type(screen.getByPlaceholderText("Issue title"), "Ordinary follow-up");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() =>+ expect(mockCreateIssue).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: "backlog", priority: "high" }),+ ),+ );+ });+});diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsxindex 0f5de7f878..66fe7ed8a3 100644--- a/packages/views/modals/create-issue.test.tsx+++ b/packages/views/modals/create-issue.test.tsx@@ -40,7 +40,9 @@ const mockSetShared = vi.hoisted(() => vi.fn());const mockSetManual = vi.hoisted(() => vi.fn());const mockSetAgent = vi.hoisted(() => vi.fn());const mockSetActiveMode = vi.hoisted(() => vi.fn());+const mockBeginBatchContinuation = vi.hoisted(() => vi.fn());const mockClearDraft = vi.hoisted(() => vi.fn());+const mockEndBatchContinuation = vi.hoisted(() => vi.fn());const mockSetLastAssignee = vi.hoisted(() => vi.fn());const mockSetKeepOpen = vi.hoisted(() => vi.fn());const mockToastCustom = vi.hoisted(() => vi.fn());@@ -127,7 +129,7 @@ const emptyIssueDraft = () => ({manual: {title: "",description: "",- status: "todo" as const,+ status: "todo" as string,startDate: null as string | null,assigneeType: undefined as "agent" | "squad" | "member" | undefined,assigneeId: undefined as string | undefined,@@ -146,13 +148,31 @@ const mockDraftStore = {draft: emptyIssueDraft(),lastAssigneeType: undefined as "agent" | "squad" | "member" | undefined,lastAssigneeId: undefined as string | undefined,+ // The keep-open reset's snapshot. Mirrors the store: the batch reset records+ // the draft it produced, so a later change is a user edit while an untouched+ // continuation is still "no draft" (see draft-store.test.ts for the+ // predicate's own coverage).+ batchContinuationBaseline: undefined as ReturnType<typeof emptyIssueDraft> | undefined,setShared: mockSetShared,setManual: mockSetManual,setAgent: mockSetAgent,setActiveMode: mockSetActiveMode,+ beginBatchContinuation: mockBeginBatchContinuation,+ endBatchContinuation: mockEndBatchContinuation,clearDraft: mockClearDraft,setLastAssignee: mockSetLastAssignee,- hasDraft: () => false,+ hasDraft: () => !!(+ mockDraftStore.draft.manual.title ||+ mockDraftStore.draft.manual.description ||+ mockDraftStore.draft.agent.prompt ||+ Object.keys(mockDraftStore.draft.manual.propertyValues).length > 0 ||+ mockDraftStore.draft.shared.attachments.some((upload) =>+ upload.status === "uploaded" || upload.status === "uploading") ||+ // Every setter below rebuilds `draft`, so a changed reference means the+ // continuation was edited.+ (mockDraftStore.batchContinuationBaseline !== undefined &&+ mockDraftStore.draft !== mockDraftStore.batchContinuationBaseline)+ ),};const mockQuickCreateStore = {@@ -441,7 +461,11 @@ vi.mock("../editor", async () => {vi.mock("../issues/components", () => ({StatusIcon: ({ status }: { status: string }) => <span data-testid="status-icon">{status}</span>,StatusPicker: () => <div data-testid="status-picker" />,- PriorityPicker: () => <div data-testid="priority-picker" />,+ // Surface onUpdate so tests can drive a field-only edit (priority is not+ // part of the draft's recoverable content).+ PriorityPicker: ({ onUpdate }: { onUpdate: (u: { priority: string }) => void }) => (+ <div data-testid="priority-picker" onClick={() => onUpdate({ priority: "high" })} />+ ),StagePicker: () => <div data-testid="stage-picker" />,AssigneePicker: () => <div data-testid="assignee-picker" />,// Surface open/onOpenChange so tests can assert progressive-disclosure@@ -634,20 +658,64 @@ describe("CreateIssueModal", () => {// Reset the unified draft mock so per-test seeding (assignee, project, …)// doesn't leak into the next test in the suite.mockDraftStore.draft = emptyIssueDraft();+ mockDraftStore.lastAssigneeType = undefined;+ mockDraftStore.lastAssigneeId = undefined;+ mockDraftStore.batchContinuationBaseline = undefined;+ mockSetLastAssignee.mockImplementation((type, id) => {+ mockDraftStore.lastAssigneeType = type;+ mockDraftStore.lastAssigneeId = id;+ });+ // Each write rebuilds `draft`, matching the real store — the keep-open+ // baseline is held by reference and must not see later edits.mockSetShared.mockImplementation((patch: Partial<typeof mockDraftStore.draft.shared>) => {- mockDraftStore.draft.shared = { ...mockDraftStore.draft.shared, ...patch };+ mockDraftStore.draft = {+ ...mockDraftStore.draft,+ shared: { ...mockDraftStore.draft.shared, ...patch },+ };});mockSetManual.mockImplementation((patch: Partial<typeof mockDraftStore.draft.manual>) => {- mockDraftStore.draft.manual = { ...mockDraftStore.draft.manual, ...patch };+ mockDraftStore.draft = {+ ...mockDraftStore.draft,+ manual: { ...mockDraftStore.draft.manual, ...patch },+ };});mockSetAgent.mockImplementation((patch: Partial<typeof mockDraftStore.draft.agent>) => {- mockDraftStore.draft.agent = { ...mockDraftStore.draft.agent, ...patch };+ mockDraftStore.draft = {+ ...mockDraftStore.draft,+ agent: { ...mockDraftStore.draft.agent, ...patch },+ };});- mockClearDraft.mockImplementation(() => {+ mockBeginBatchContinuation.mockImplementation(() => {+ mockDraftStore.batchContinuationBaseline = mockDraftStore.draft;+ });+ const resetMockDraft = () => {const next = emptyIssueDraft();next.manual.assigneeType = mockDraftStore.lastAssigneeType;next.manual.assigneeId = mockDraftStore.lastAssigneeId;mockDraftStore.draft = next;+ mockDraftStore.batchContinuationBaseline = undefined;+ };+ mockClearDraft.mockImplementation(resetMockDraft);+ // Mirrors the store's close-time cleanup: nothing to end without a live+ // continuation snapshot (a source-context close restored the ordinary+ // draft), a continuation whose manual form is still what the reset wrote+ // loses only the status the batch inherited, and one the user actually+ // edited closes as it is — inherited status included. The agent slot and+ // `activeMode` stay out of the comparison: a mode switch is not an edit.+ mockEndBatchContinuation.mockImplementation(() => {+ const baseline = mockDraftStore.batchContinuationBaseline;+ if (!baseline) return;+ const { draft } = mockDraftStore;+ const unchanged =+ JSON.stringify({ shared: draft.shared, manual: draft.manual }) ===+ JSON.stringify({ shared: baseline.shared, manual: baseline.manual });+ if (unchanged) {+ mockDraftStore.draft = {+ ...draft,+ manual: { ...draft.manual, status: "todo" },+ };+ }+ mockDraftStore.batchContinuationBaseline = undefined;});mockApiUploadFile.mockResolvedValue({id: "11111111-2222-3333-4444-555555555555",@@ -762,6 +830,35 @@ describe("CreateIssueModal", () => {expect(mockToastDismiss).toHaveBeenCalledWith("toast-1");});+ it("starts a fresh create from todo without a remembered stage", async () => {+ const user = userEvent.setup();+ const first = renderModal(<CreateIssueModal onClose={vi.fn()} data={{+ parent_issue_id: "parent-1",+ status: "in_progress",+ stage: 2,+ }} />);++ fireEvent.change(screen.getByPlaceholderText("Issue title"), {+ target: { value: "Follow up" },+ });+ await user.click(screen.getByRole("button", { name: "Create Issue" }));++ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalledWith(+ expect.objectContaining({ status: "in_progress", parent_issue_id: "parent-1", stage: 2 }),+ ));+ first.unmount();+ renderModal(<CreateIssueModal onClose={vi.fn()} data={{ parent_issue_id: "parent-1" }} />);++ fireEvent.change(screen.getByPlaceholderText("Issue title"), {+ target: { value: "Another child" },+ });+ await user.click(screen.getByRole("button", { name: "Create Issue" }));++ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalledWith(+ expect.objectContaining({ status: "todo", parent_issue_id: "parent-1", stage: undefined }),+ ));+ });+it("forwards selected labels in the create payload so they attach in the same transaction", async () => {const user = userEvent.setup();mockDraftStore.draft.manual.labelIds = [@@ -827,12 +924,16 @@ describe("CreateIssueModal", () => {});});- it("keeps manual mode open and clears content when create another is enabled", async () => {+ it("keeps status, assignee, parent, and stage for the next issue in a batch", async () => {const user = userEvent.setup();const onClose = vi.fn();mockQuickCreateStore.keepOpen = true;+ mockDraftStore.draft.manual.assigneeType = "member";+ mockDraftStore.draft.manual.assigneeId = "alice";- renderModal(<CreateIssueModal onClose={onClose} />);+ const modal = renderModal(<CreateIssueModal onClose={onClose} data={{+ parent_issue_id: "parent-1", status: "in_progress", stage: 2,+ }} />);await user.type(screen.getByPlaceholderText("Issue title"), "First follow-up issue");await user.type(screen.getByPlaceholderText("Add description..."), "Description to clear");@@ -842,14 +943,15 @@ describe("CreateIssueModal", () => {expect(mockCreateIssue).toHaveBeenCalledWith({title: "First follow-up issue",description: "Description to clear",- status: "todo",+ status: "in_progress",priority: "none",- assignee_type: undefined,- assignee_id: undefined,+ assignee_type: "member",+ assignee_id: "alice",start_date: undefined,due_date: undefined,attachment_ids: undefined,- parent_issue_id: undefined,+ parent_issue_id: "parent-1",+ stage: 2,project_id: undefined,});});@@ -860,9 +962,9 @@ describe("CreateIssueModal", () => {expect(mockSetManual).toHaveBeenCalledWith({title: "",description: "",- status: "todo",- assigneeType: undefined,- assigneeId: undefined,+ status: "in_progress",+ assigneeType: "member",+ assigneeId: "alice",startDate: null,labelIds: [],propertyValues: {},@@ -873,6 +975,82 @@ describe("CreateIssueModal", () => {dueDate: null,attachments: [],});++ await user.type(screen.getByPlaceholderText("Issue title"), "Second follow-up issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalledTimes(2));+ expect(mockCreateIssue).toHaveBeenNthCalledWith(2, expect.objectContaining({+ title: "Second follow-up issue",+ status: "in_progress",+ assignee_type: "member",+ assignee_id: "alice",+ parent_issue_id: "parent-1",+ stage: 2,+ }));++ // An untouched continuation is not a draft: closing it drops the batch+ // defaults so the next fresh create starts from todo again.+ const endsAfterSubmit = mockEndBatchContinuation.mock.calls.length;+ modal.unmount();+ expect(mockEndBatchContinuation).toHaveBeenCalledTimes(endsAfterSubmit + 1);+ expect(mockDraftStore.draft.manual.status).toBe("todo");+ renderModal(<CreateIssueModal onClose={vi.fn()} />);+ await user.type(screen.getByPlaceholderText("Issue title"), "Fresh issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalledTimes(3));+ expect(mockCreateIssue).toHaveBeenNthCalledWith(3, expect.objectContaining({+ status: "todo", parent_issue_id: undefined, stage: undefined,+ }));+ });++ it("keeps a field-only edit in the next batch issue when the dialog closes", async () => {+ const user = userEvent.setup();+ mockQuickCreateStore.keepOpen = true;++ const modal = renderModal(<CreateIssueModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText("Issue title"), "First issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ // The submitted draft is consumed, leaving an untouched continuation.+ await waitFor(() => expect(mockClearDraft).toHaveBeenCalledTimes(1));+ const endsAfterSubmit = mockEndBatchContinuation.mock.calls.length;++ // Priority only — no title, body or attachment to mark the draft as content.+ await user.click(screen.getByTestId("priority-picker"));+ expect(mockSetShared).toHaveBeenCalledWith({ priority: "high" });++ modal.unmount();++ // The explicit selection survives alongside this batch's todo status.+ expect(mockEndBatchContinuation).toHaveBeenCalledTimes(endsAfterSubmit + 1);+ expect(mockDraftStore.draft.shared.priority).toBe("high");+ expect(mockDraftStore.draft.manual.status).toBe("todo");++ renderModal(<CreateIssueModal onClose={vi.fn()} />);+ await user.type(screen.getByPlaceholderText("Issue title"), "Carried priority issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() => expect(mockCreateIssue).toHaveBeenLastCalledWith(+ expect.objectContaining({ priority: "high" }),+ ));+ });++ it("preserves an unfinished next issue instead of clearing it on close", async () => {+ const user = userEvent.setup();+ mockQuickCreateStore.keepOpen = true;+ const modal = renderModal(<CreateIssueModal onClose={vi.fn()} data={{+ status: "in_progress",+ }} />);++ await user.type(screen.getByPlaceholderText("Issue title"), "First issue");+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ await waitFor(() => expect(screen.getByPlaceholderText("Issue title")).toHaveValue(""));+ await user.type(screen.getByPlaceholderText("Issue title"), "Unfinished next issue");+ modal.unmount();++ expect(mockDraftStore.draft.manual.title).toBe("Unfinished next issue");+ expect(mockDraftStore.draft.manual.status).toBe("in_progress");+ renderModal(<CreateIssueModal onClose={vi.fn()} />);+ expect(screen.getByPlaceholderText("Issue title")).toHaveValue("Unfinished next issue");});it("includes configured custom properties in the atomic create request", async () => {diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex ea3136aaf7..7e35e89dc4 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -263,6 +263,7 @@ export function ManualCreatePanel({const setShared = useIssueDraftStore((s) => s.setShared);const setAgent = useIssueDraftStore((s) => s.setAgent);const setActiveMode = useIssueDraftStore((s) => s.setActiveMode);+ const beginBatchContinuation = useIssueDraftStore((s) => s.beginBatchContinuation);const clearDraft = useIssueDraftStore((s) => s.clearDraft);const setLastAssignee = useIssueDraftStore((s) => s.setLastAssignee);const setLastMode = useCreateModeStore((s) => s.setLastMode);@@ -315,8 +316,7 @@ export function ManualCreatePanel({const parentIssueLocked = anchorCommentId !== null&& typeof data?.parent_issue_id === "string"&& data.parent_issue_id.length > 0;- // Stage only applies to a sub-issue; kept local (not in the persisted draft)- // since it's a per-creation choice tied to the chosen parent.+ // Stage belongs to this create session and only applies to a sub-issue.const [stage, setStage] = useState<number | null>(typeof data?.stage === "number" ? (data.stage as number) : null,);@@ -411,6 +411,10 @@ export function ManualCreatePanel({setManual({ assigneeType: type, assigneeId: id });};const updateProject = (id?: string) => { setProjectId(id); setShared({ projectId: id }); };+ const updateParent = (id?: string) => {+ setParentIssueId(id);+ setStage(null);+ };// A project using a named workflow only accepts its columns: a status it// does not list moves to todo, which every workflow keeps. (MUL-7420)const createWorkflow = useProjectWorkflow(wsId, projectId);@@ -451,7 +455,7 @@ export function ManualCreatePanel({const attachLabelMutation = useAttachLabelToIssue();const resetForNextIssue = () => {setTitle("");- setStatus("todo");+ setStatus(status);setPriority("none");setStartDate(null);setDueDate(null);@@ -461,15 +465,13 @@ export function ManualCreatePanel({setPropertyErrorId(null);setUnavailablePropertyRemoved(false);setProjectId(undefined);- setParentIssueId(undefined);- setStage(null);setChildIssues([]);- // Keep the just-used assignee for the next issue in the batch; reset- // everything else across the manual + shared slots.+ // Keep status and assignee in this batch. Parent and stage stay in local+ // state, while other manual and shared fields reset for the next issue.setManual({title: "",description: "",- status: "todo",+ status,assigneeType,assigneeId,startDate: null,@@ -482,8 +484,14 @@ export function ManualCreatePanel({dueDate: null,attachments: [],});+ // The reset above is a batch continuation, not user input: record it so a+ // field the user actually changes afterwards (priority, a date, a label —+ // anything `hasDraft` alone would not consider content) keeps the draft+ // recoverable, while a continuation nobody touched is still discarded.+ beginBatchContinuation();descEditorRef.current?.clearContent();setFormResetKey((key) => key + 1);+ batchContinuationRef.current = true;};// Manual create runs through the shared await-then-render composer contract@@ -497,10 +505,19 @@ export function ManualCreatePanel({// object identity at submit; success clears ONLY an untouched draft —// whether the edit came mid-flight or from a reopened dialog.const mountedRef = useRef(true);+ const batchContinuationRef = useRef(false);useLayoutEffect(() => {mountedRef.current = true;return () => {mountedRef.current = false;+ // A keep-open form nobody edited is only a batch continuation. Ending it+ // as the form closes drops the inherited batch status, so the next fresh+ // dialog starts from todo, while a continuation the user did edit keeps+ // its fields. The store action decides, and no-ops when a source-context+ // wrapper already restored the ordinary draft.+ if (batchContinuationRef.current) {+ useIssueDraftStore.getState().endBatchContinuation();+ }};}, []);const submittedDraftRef = useRef<IssueCreateDraft | null>(null);@@ -790,8 +807,7 @@ export function ManualCreatePanel({}},onAccepted: () => {- // These preferences derive from the SUBMITTED values, not the live- // draft — an issue was created, so record them regardless of the guard.+ // Only the assignee persists across independent create sessions.setLastAssignee(assigneeType, assigneeId);setLastMode("manual");// Success may only consume the draft it submitted (MUL-5181 P0): any@@ -1234,7 +1250,7 @@ export function ManualCreatePanel({<TooltipHint label={t(($) => $.create_issue.remove_parent_aria)}><buttontype="button"- onClick={() => setParentIssueId(undefined)}+ onClick={() => updateParent(undefined)}className="p-1 pr-2 text-muted-foreground hover:text-foreground cursor-pointer"aria-label={t(($) => $.create_issue.remove_parent_aria)}>@@ -1403,7 +1419,7 @@ export function ManualCreatePanel({<DropdownMenuSeparator /><DropdownMenuItemvariant="destructive"- onClick={() => setParentIssueId(undefined)}+ onClick={() => updateParent(undefined)}><XIcon className="h-3.5 w-3.5" />{t(($) => $.create_issue.remove_parent)}@@ -1432,7 +1448,7 @@ export function ManualCreatePanel({...(parentIssueId ? [parentIssueId] : []),]}onSelect={(selected) => {- setParentIssueId(selected.id);+ updateParent(selected.id);}}/><IssuePickerModal