Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

6.3 KB
Raw Blame
import AsyncStorage from "@react-native-async-storage/async-storage";
import { getMobileAuthOwner, isMobileAuthOwnerCurrent, type MobileAuthOwnerGeneration } from '@/auth/authOwnerGeneration';
import { createDurableOutbox, isDurableOutboxSettled, type DurableOutboxRecord } from "./durableOutbox";
import { durableOutboxUploadUri, removeOutboxFiles } from "./durableOutboxFiles";
import { outboxItemAttachments, type MobileOutboxItem } from "./sessionOutbox";
import { discardMobileUploadedAttachment } from "./mobileAttachmentUpload";
import type { RemoteSerializedAttachment } from "./types";
import { reconcileCommittedComposerDraft } from './composerDraftStore';
import { withAsyncStorageFullRecovery } from './asyncStorageFull';
import { migrateLegacySessionMessageCache } from './mobileSessionMessageCache';
import { cancelledCreationDraft } from './cancelledCreationDraft';

const outboxStorage = withAsyncStorageFullRecovery(AsyncStorage, migrateLegacySessionMessageCache);
export const mobileDurableOutbox = createDurableOutbox(outboxStorage, async (record, guard) => {
  if (!record.draftHandoff) return;
  const owner = getMobileAuthOwner();
  const check = () => {
    guard();
    if (owner.accountKey !== record.accountId || !isMobileAuthOwnerCurrent(owner)) {
      throw new Error('OUTBOX_OWNER_CHANGED');
    }
  };
  await reconcileCommittedComposerDraft(record.item.sessionId, record.draftHandoff, check);
});

/** Persist before destructive cleanup: an account switch may discard its reply. */
export async function suspendCreationDraftForCleanup(record: { sessionId: string; deviceId: string }): Promise<void> {
  const owner = getMobileAuthOwner();
  const guard = () => {
    if (!owner.accountKey || !isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');
  };
  guard();
  await mobileDurableOutbox.activate(owner.accountKey);
  guard();
  for (const draft of getCurrentMobileOutboxRecords().filter(r =>
    r.deviceId === record.deviceId && r.item.sessionId === record.sessionId && r.creation)) {
    guard();
    // This also refuses records with send evidence before any destructive call.
    cancelledCreationDraft(draft);
    if (!draft.suspended) await mobileDurableOutbox.update(draft, { suspended: true });
  }
  guard();
}

/** Host ACK must be followed by this durable write before the recovery ledger is removed. */
export async function persistCancelledCreationDraft(record: { sessionId: string; deviceId: string; originalWorkingDir?: string }): Promise<void> {
  const owner = getMobileAuthOwner();
  const guard = () => {
    if (!owner.accountKey || !isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');
  };
  guard();
  await mobileDurableOutbox.activate(owner.accountKey);
  guard();
  const drafts = mobileDurableOutbox.getSnapshot().filter((r) =>
    r.deviceId === record.deviceId && r.item.sessionId === record.sessionId && r.creation);
  for (const draft of drafts) {
    guard();
    const next = record.originalWorkingDir !== undefined
      ? { ...draft, creation: { ...draft.creation!, originalWorkingDir: record.originalWorkingDir } }
      : draft;
    await mobileDurableOutbox.update(draft, cancelledCreationDraft(next));
  }
  guard();
}
export async function reconcileMobileOutboxDrafts(sessionId: string): Promise<void> {
  const owner = getMobileAuthOwner();
  if (!owner.accountKey) return;
  await mobileDurableOutbox.activate(owner.accountKey);
  if (!isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');
  await mobileDurableOutbox.reconcileDrafts(sessionId);
}
/** Local filesystem failures must not suppress disposal of confirmed-cancelled uploads. */
export async function cleanupOutboxResources(
  record: DurableOutboxRecord,
  owner: MobileAuthOwnerGeneration,
  getToken: () => Promise<string | null>,
  cancelled: boolean,
): Promise<void> {
  try {
    await removeOutboxFiles(record);
  } finally {
    if (cancelled) discardOutboxUploads(record, owner, getToken);
  }
}
/** Hide old-owner rows even before the bridge's React effect activates the next ledger. */
export function getCurrentMobileOutboxRecords(): readonly DurableOutboxRecord[] {
  const key = getMobileAuthOwner().accountKey;
  return mobileDurableOutbox.getSnapshot().filter((record) => record.accountId === key && !isDurableOutboxSettled(record));
}
/** Call only for confirmed cancellation, superseded references, or an upload never handed to the ledger. */
export function discardOutboxUploads(
  record: DurableOutboxRecord,
  owner: MobileAuthOwnerGeneration,
  getToken: () => Promise<string | null>,
  attachments: readonly RemoteSerializedAttachment[] = outboxItemAttachments(record.item),
): void {
  if (record.accountId !== owner.accountKey) return;
  for (const attachment of attachments) {
    discardMobileUploadedAttachment(attachment, { getToken: async () => {
      if (!isMobileAuthOwnerCurrent(owner)) return null;
      const token = await getToken();
      return isMobileAuthOwnerCurrent(owner) ? token : null;
    } });
  }
}
export function durableOutboxDisplayItem(
  record: DurableOutboxRecord,
): MobileOutboxItem {
  return {
    ...record.item,
    phase:
      record.state === "failed"
        ? "failed"
        : record.state === "sending" ||
            record.state === "confirming" ||
            record.state === "host-owned"
          ? "dispatching"
          : "uploading",
    enqueueError: record.error ?? null,
    ...(record.failedUploadSlot !== undefined ? { failedUploadSlot: record.failedUploadSlot } : {}),
    slotMeta: record.item.slotMeta.map((meta, slot) => {
      const upload = record.uploads.find((u) => u.slot === slot);
      return upload
        ? { ...meta, previewUri: durableOutboxUploadUri(record, upload) }
        : meta;
    }),
  };
}

// Synchronous reservation covers the disk-write -> live creation task registration window.
const creationHolds = new Map<string, number>();
export function holdDurableOutboxCreation(sessionId: string): () => void {
  creationHolds.set(sessionId, (creationHolds.get(sessionId) ?? 0) + 1);
  let released = false;
  return () => {
    if (released) return;
    released = true;
    const count = (creationHolds.get(sessionId) ?? 1) - 1;
    if (count) creationHolds.set(sessionId, count);
    else creationHolds.delete(sessionId);
  };
}
export function isDurableOutboxCreationHeld(sessionId: string): boolean {
  return creationHolds.has(sessionId);
}