All files / src/apps/user/pages/agents/setup draftStore.ts

97.91% Statements 47/48
94.44% Branches 34/36
100% Functions 9/9
97.72% Lines 43/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126                        3x     3x   3x 124x                         3x 9008x 8122x 6135x 1523x 7811x     4612x     3x 141x 116x 41x 41x 14x   27x 120x     75x     3x 124x 124x           3x         91x 91x 91x                 3x 10x 10x           3x       23x 23x 23x   1x   22x 5x 5x       5x 23x           2x                     3x 3x    
/**
 * The generative agent wizard's working copy, kept in this tab's
 * sessionStorage so a reload — or the app's error page, which reloads —
 * does not throw away a generation that has already been paid for.
 *
 * Per viewer, per tab, per workspace, and only a convenience: storage may
 * be blocked, full or cleared, so every access is guarded and the wizard
 * works without it. A copy older than a day is not offered (what it
 * selected may have changed since); one the code cannot read is dropped.
 */
 
/** Bumped when what is stored changes shape, so an old copy is ignored. */
export const DRAFT_VERSION = 1;
 
/** How long a stored copy is offered back. */
export const DRAFT_TTL_MS = 24 * 60 * 60 * 1000;
 
const keyFor = (workspaceKey: string): string =>
  `chainr.agentSetup.${workspaceKey}`;
 
/** What is stored: the wizard's own fields, its draft with every `Set`
 *  written as an array (`Set`s do not survive JSON). */
export interface StoredWizard<Draft> {
  problem: string;
  modelId: string;
  step: string;
  draft: Draft;
  /** When it was saved, ms since the epoch. */
  savedAt: number;
}
 
const encode = (value: unknown): unknown => {
  if (value instanceof Set) return { __set: [...value] };
  if (Array.isArray(value)) return value.map(encode);
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value).map(([k, v]) => [k, encode(v)]),
    );
  }
  return value;
};
 
const decode = (value: unknown): unknown => {
  if (Array.isArray(value)) return value.map(decode);
  if (value && typeof value === "object") {
    const record = value as Record<string, unknown>;
    if (Array.isArray(record.__set) && Object.keys(record).length === 1) {
      return new Set(record.__set);
    }
    return Object.fromEntries(
      Object.entries(record).map(([k, v]) => [k, decode(v)]),
    );
  }
  return value;
};
 
const storage = (): Storage | null => {
  try {
    return window.sessionStorage;
  } catch {
    return null;
  }
};
 
export const saveDraft = <Draft>(
  workspaceKey: string,
  wizard: Omit<StoredWizard<Draft>, "savedAt">,
  now: number = Date.now(),
): void => {
  const stored = encode({ ...wizard, savedAt: now }) as Record<string, unknown>;
  try {
    storage()?.setItem(
      keyFor(workspaceKey),
      JSON.stringify({ version: DRAFT_VERSION, ...stored }),
    );
  } catch {
    // Full or blocked: the wizard carries on, only without a copy.
  }
};
 
export const clearDraft = (workspaceKey: string): void => {
  try {
    storage()?.removeItem(keyFor(workspaceKey));
  } catch {
    // Nothing to clear where storage cannot be reached.
  }
};
 
export const loadDraft = <Draft>(
  workspaceKey: string,
  now: number = Date.now(),
): StoredWizard<Draft> | null => {
  let raw: string | null = null;
  try {
    raw = storage()?.getItem(keyFor(workspaceKey)) ?? null;
  } catch {
    return null;
  }
  if (!raw) return null;
  try {
    const parsed = decode(JSON.parse(raw)) as Partial<StoredWizard<Draft>> & {
      version?: number;
    };
    const fresh =
      typeof parsed.savedAt === "number" && now - parsed.savedAt < DRAFT_TTL_MS;
    if (
      parsed.version === DRAFT_VERSION &&
      fresh &&
      parsed.draft &&
      typeof parsed.step === "string"
    ) {
      return {
        problem: String(parsed.problem ?? ""),
        modelId: String(parsed.modelId ?? ""),
        step: parsed.step,
        draft: parsed.draft as Draft,
        savedAt: parsed.savedAt as number,
      };
    }
  } catch {
    // Unreadable: dropped below.
  }
  clearDraft(workspaceKey);
  return null;
};