Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
16.1 KB
Raw Blame
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import type {
  IssueStatus,
  IssuePriority,
  IssueAssigneeType,
  IssuePropertyValues,
} from "../../types";
import type { CreateMode } from "./create-mode-store";
import type { QuickCreateActorType } from "./quick-create-store";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
import { registerDraftCleanup } from "../../drafts/cleanup-registry";
import { normalizeStoredUploads, type DraftUpload } from "../../drafts/draft-upload";

// One logical Issue-Create draft (MUL-5181), split so switching between the
// manual form and the agent form never destroys the other side's content.
//
//   shared  — belongs to the issue no matter how it is filed: project,
//             priority, due date, attachments.
//   manual  — the manual form's own state: title, description, status, start
//             date, assignee, labels, custom properties.
//   agent   — the agent form's own state: the free-text prompt and the picked
//             actor (agent or squad).
//   activeMode — which form the draft is currently being edited in.
//
// Before this split, `switchToAgent` concatenated title + description into the
// prompt and then CLEARED the manual fields, and `switchToManual` copied the
// prompt into the description but left the old prompt behind — so a round-trip
// both lost manual content and resurfaced a stale prompt. With separate slots
// a switch is a no-op on the other side's data; the only cross-write is a
// one-time assist-init the panels perform when the target slot is still empty.

export interface IssueCreateShared {
  projectId?: string;
  priority: IssuePriority;
  dueDate: string | null;
  /** Uploads for the dialog (placeholders + completed), referenced by the
   *  manual description OR the agent prompt markdown. A single pool so an
   *  image survives a mode switch from either side; each submit path sends
   *  only the ids its own content references. Coordinator-owned (MUL-5181 L2):
   *  a placeholder written at pick time survives dialog close, and one still
   *  `uploading` at load time is dropped on rehydrate. */
  attachments: DraftUpload[];
}

export interface IssueCreateManual {
  title: string;
  description: string;
  status: IssueStatus;
  startDate: string | null;
  assigneeType?: IssueAssigneeType;
  assigneeId?: string;
  /** The assignee last picked by hand in this draft, not yet counted toward
   *  the picker's local ranking. A create submitting this same assignee
   *  counts it once; a prefilled assignee never matches it. */
  assigneePick?: { type: IssueAssigneeType; id: string };
  /** Label IDs chosen in the create dialog. Attached to the issue right after
   *  it is created (the create endpoint takes no labels), so they are kept as
   *  a plain id list rather than full Label objects. */
  labelIds: string[];
  propertyValues: IssuePropertyValues;
}

export interface IssueCreateAgent {
  prompt: string;
  actorType?: QuickCreateActorType;
  actorId?: string;
}

export interface IssueCreateDraft {
  shared: IssueCreateShared;
  manual: IssueCreateManual;
  agent: IssueCreateAgent;
  activeMode: CreateMode;
}

const emptyShared = (): IssueCreateShared => ({
  projectId: undefined,
  priority: "none",
  dueDate: null,
  attachments: [],
});

const emptyManual = (): IssueCreateManual => ({
  title: "",
  description: "",
  status: "todo",
  startDate: null,
  assigneeType: undefined,
  assigneeId: undefined,
  labelIds: [],
  propertyValues: {},
});

const emptyAgent = (): IssueCreateAgent => ({
  prompt: "",
  actorType: undefined,
  actorId: undefined,
});

interface IssueDraftStore {
  draft: IssueCreateDraft;
  /** In-memory only. While present, writes target an isolated source-context
   *  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.
  lastAssigneeType?: IssueAssigneeType;
  lastAssigneeId?: string;
  setShared: (patch: Partial<IssueCreateShared>) => void;
  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;
  setLastAssignee: (type?: IssueAssigneeType, id?: string) => void;
  hasDraft: () => boolean;
}

function isLegacyFlatDraft(d: Record<string, unknown>): boolean {
  return (
    !("manual" in d) &&
    !("shared" in d) &&
    ("title" in d || "status" in d || "labelIds" in d || "description" in d)
  );
}

// Drafts persisted by older builds either predate a later-added sub-field or
// use the pre-MUL-5181 flat shape. Backfill defaults so every read site can
// rely on the declared IssueCreateDraft shape instead of re-defending, and lift
// a legacy flat draft into the manual/shared slots (there was no agent prompt
// in that store — it lived in `multica_quick_create` and is not carried over).
function migrateDraft(raw: unknown): IssueCreateDraft {
  const d = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;

  if (isLegacyFlatDraft(d)) {
    return {
      shared: {
        ...emptyShared(),
        projectId: d.projectId as string | undefined,
        priority: (d.priority as IssuePriority) ?? "none",
        dueDate: (d.dueDate as string | null) ?? null,
        // Legacy builds persisted bare Attachment rows; normalize wraps them
        // as `uploaded` placeholders (and drops stale `uploading` ones).
        attachments: normalizeStoredUploads(d.attachments),
      },
      manual: {
        ...emptyManual(),
        title: (d.title as string) ?? "",
        description: (d.description as string) ?? "",
        status: (d.status as IssueStatus) ?? "todo",
        startDate: (d.startDate as string | null) ?? null,
        assigneeType: d.assigneeType as IssueAssigneeType | undefined,
        assigneeId: d.assigneeId as string | undefined,
        labelIds: Array.isArray(d.labelIds) ? (d.labelIds as string[]) : [],
        propertyValues:
          d.propertyValues && typeof d.propertyValues === "object"
            ? (d.propertyValues as IssuePropertyValues)
            : {},
      },
      agent: emptyAgent(),
      activeMode: "manual",
    };
  }

  const sharedRaw = (d.shared as Partial<IssueCreateShared> & { attachments?: unknown }) ?? {};
  return {
    shared: {
      ...emptyShared(),
      ...sharedRaw,
      // Pre-L2 nested drafts stored bare Attachment rows; every load also
      // drops `uploading` placeholders (bytes are gone).
      attachments: normalizeStoredUploads(sharedRaw.attachments),
    },
    manual: { ...emptyManual(), ...((d.manual as Partial<IssueCreateManual>) ?? {}) },
    agent: { ...emptyAgent(), ...((d.agent as Partial<IssueCreateAgent>) ?? {}) },
    activeMode: d.activeMode === "agent" ? "agent" : "manual",
  };
}

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) => ({
      draft: migrateDraft(undefined),
      lastAssigneeType: undefined,
      lastAssigneeId: undefined,
      setShared: (patch) =>
        set((s) => ({ draft: { ...s.draft, shared: { ...s.draft.shared, ...patch } } })),
      setManual: (patch) =>
        set((s) => ({ draft: { ...s.draft, manual: { ...s.draft.manual, ...patch } } })),
      setAgent: (patch) =>
        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: {
            shared: emptyShared(),
            manual: {
              ...emptyManual(),
              assigneeType: s.lastAssigneeType,
              assigneeId: s.lastAssigneeId,
            },
            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: {
                ...emptyManual(),
                assigneeType: s.lastAssigneeType,
                assigneeId: s.lastAssigneeId,
              },
              agent: emptyAgent(),
              activeMode: "agent",
            },
          };
        }),
      endIsolatedDraft: () =>
        set((s) => s.isolatedDraftBackup
          ? { draft: s.isolatedDraftBackup, isolatedDraftBackup: undefined, batchContinuationBaseline: undefined }
          : s),
      setLastAssignee: (type, id) =>
        set({ lastAssigneeType: type, lastAssigneeId: id }),
      hasDraft: () => {
        const { draft, batchContinuationBaseline } = get();
        return hasRecoverableIntent(draft, batchContinuationBaseline);
      },
    }),
    {
      name: "multica_issue_draft",
      storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
      // 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) => {
        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,
          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,
        };
      },
    },
  ),
);

registerForWorkspaceRehydration(() => useIssueDraftStore.persist.rehydrate());

registerDraftCleanup({
  storageKey: "multica_issue_draft",
  workspaceScoped: true,
  // Full reset, NOT clearDraft(): clearDraft deliberately keeps the
  // last-assignee preference and re-seeds it into the fresh draft's manual
  // slot — correct between drafts of one user, but on logout it would hand
  // the previous user's last-picked assignee to the next login on this tab.
  resetInMemory: () =>
    useIssueDraftStore.setState({
      draft: migrateDraft(undefined),
      lastAssigneeType: undefined,
      lastAssigneeId: undefined,
      isolatedDraftBackup: undefined,
      batchContinuationBaseline: undefined,
    }),
});