Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
import { ErrorNotice } from '@/components/ui/error-notice';
import { useEffect, useRef, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Tip } from '@/components/ui/tooltip';
import { MakeDoctorReportCard } from '@/components/chat/CindyMakeDoctorCard';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
} from '@/contexts/dataOwnerGeneration';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import { startMakeDoctor, cancelMakeDoctor } from '@/lib/cindyMakeDoctor';
import { toast } from '@/lib/toast';
import type { CindyMakeTaskOptions, MakeDoctorReport } from '../../../shared/cindyMakeDoctor';
export interface CindyMakePreflightProps {
request: string;
sessionId?: string;
createOptions?: CindyMakeTaskOptions;
onOpenChange: (open: boolean) => void;
}
/**
* Continue is offered once the official lookup finished, also when it failed: not
* knowing whether a similar official change exists never blocks making one.
*/
const LOOKUP_FINISHED = ['found', 'notFound', 'failed'];
/** Checks belong to this dialog; only Continue creates a persistent task. */
export function CindyMakePreflightDialog({
request,
sessionId,
createOptions,
onOpenChange,
}: CindyMakePreflightProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const [report, setReport] = useState<MakeDoctorReport>();
const [attempt, setAttempt] = useState(0);
const [starting, setStarting] = useState(false);
const [failed, setFailed] = useState(false);
const [confirmClose, setConfirmClose] = useState(false);
const submitting = useRef(false);
const contentRef = useRef<HTMLDivElement>(null);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const mounted = useRef(false);
const owner = useRef(getDataOwnerGeneration());
const returnFocus = useRef(
document.activeElement instanceof HTMLElement ? document.activeElement : null,
);
const current = () =>
mounted.current &&
isDataOwnerGenerationCurrent(owner.current) &&
!getStickySessionDeviceId(sessionId);
useEffect(() => {
mounted.current = true;
const controller = new AbortController();
let latest: MakeDoctorReport | undefined;
// StrictMode rehearses effect cleanup before the real mount. Do not dispatch
// a run from that discarded effect and immediately cancel the shared checks.
queueMicrotask(() => {
if (
controller.signal.aborted ||
!isDataOwnerGenerationCurrent(owner.current) ||
getStickySessionDeviceId(sessionId)
)
return;
startMakeDoctor(
(next) => {
latest = next;
setReport(next);
},
undefined,
'cindy-make',
{ request, signal: controller.signal },
);
});
return () => {
mounted.current = false;
controller.abort();
if (latest?.status === 'running' && isDataOwnerGenerationCurrent(owner.current))
void cancelMakeDoctor(latest.runId, latest.mode).catch(() => {});
};
}, [request, sessionId, attempt]);
const start = async () => {
if (
!current() ||
submitting.current ||
confirmClose ||
report?.status !== 'completed' ||
!LOOKUP_FINISHED.includes(report.upstream?.status ?? '')
)
return;
submitting.current = true;
setStarting(true);
setFailed(false);
try {
const chars = Array.from(request.replace(/\s+/gu, ' ').trim());
const createdId = await window.electronAPI.startCindyMakeTask({
originSessionId: sessionId,
runId: report.runId,
request,
title: t('cindyMake.code.taskTitle', {
worktree: report.runId.slice(0, 4),
request: chars.slice(0, 60).join('') + (chars.length > 60 ? '…' : ''),
}),
createOptions,
});
if (!isDataOwnerGenerationCurrent(owner.current)) return;
const [{ makerChatStore }, sessionService, { sessionsStore }] = await Promise.all([
import('@/lib/makerChatStore'),
import('@/lib/sessionService'),
import('@/lib/sessionsStore'),
]);
if (!isDataOwnerGenerationCurrent(owner.current)) return;
makerChatStore.setSessionRuntime(createdId, { autoTitleDisabled: true });
const session = await sessionService.get(createdId).catch(() => null);
if (!isDataOwnerGenerationCurrent(owner.current)) return;
if (session) sessionsStore.prependCreated(session);
if (current()) {
onOpenChange(false);
navigate('/cc-agent/' + createdId);
}
} catch {
if (current()) setFailed(true);
} finally {
submitting.current = false;
if (mounted.current) setStarting(false);
}
};
const requestClose = () => {
if (!submitting.current) setConfirmClose(true);
};
const closeLabel = t(starting ? 'cindyMake.preflight.creating' : 'common.dismiss');
// Read the live report while confirmation is open: preparation may finish
// before the user decides, changing what closing will actually stop.
const closeStage =
!report || report.status === 'running'
? report?.upstream?.status === 'searching'
? 'upstream'
: report?.source?.status === 'preparing'
? 'source'
: 'environment'
: report.status === 'completed' && LOOKUP_FINISHED.includes(report.upstream?.status ?? '')
? 'ready'
: 'incomplete';
return (
<Dialog.Root open onOpenChange={(open) => !open && requestClose()}>
<Dialog.Portal>
<Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />
<Dialog.Content
ref={contentRef}
tabIndex={-1}
className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex max-h-[85vh] w-[min(600px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col gap-4 overflow-hidden p-4 outline-none"
onOpenAutoFocus={(event) => {
// The report and Continue action arrive asynchronously. Start at the
// readable content instead of making Close the initial action.
event.preventDefault();
contentRef.current?.focus({ preventScroll: true });
}}
onCloseAutoFocus={(event) => {
event.preventDefault();
returnFocus.current?.isConnected && returnFocus.current.focus();
}}
onEscapeKeyDown={(event) => {
if (submitting.current || event.isComposing || event.keyCode === 229)
event.preventDefault();
}}
>
<div className="flex shrink-0 items-center justify-between gap-4">
<Dialog.Title className="text-16 font-medium text-[var(--confirm-title)]">
{t('cindyMake.title')}
</Dialog.Title>
<Tip text={closeLabel} contentClassName="z-[10002]">
<span className="inline-flex">
<Button
ref={closeButtonRef}
variant="secondary"
className="w-8 border-transparent bg-transparent px-0 text-[var(--confirm-desc)]"
disabled={starting}
aria-label={closeLabel}
onClick={requestClose}
>
<X size={16} aria-hidden />
</Button>
</span>
</Tip>
</div>
<div className="min-h-0 space-y-4 overflow-y-auto">
<Dialog.Description className="whitespace-pre-wrap break-words text-13 text-[var(--confirm-desc)]">
{request}
</Dialog.Description>
{report && (
<MakeDoctorReportCard
report={report}
request={request}
startingCode={starting}
showUpstreamActions={false}
onRecheck={() => {
if (!submitting.current && !confirmClose && current()) {
setFailed(false);
setAttempt((value) => value + 1);
}
}}
onStop={() => {
if (!confirmClose && current())
void cancelMakeDoctor(report.runId, report.mode).catch(() =>
toast.error(t('cindyMakeDoctor.failed')),
);
}}
/>
)}
{failed && (
<ErrorNotice role="alert" message={t('cindyMake.code.preparationFailed')} />
)}
</div>
{report?.status === 'completed' &&
LOOKUP_FINISHED.includes(report.upstream?.status ?? '') && (
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
{report.upstream?.status === 'failed' && (
<p className="mr-auto text-12 text-[var(--text-secondary)]">
{t('cindyMake.upstream.failedContinue')}
</p>
)}
<Button
variant="primary"
className="border-[var(--border-default)] enabled:hover:border-[var(--button-primary-hover)] enabled:active:border-[var(--button-primary-pressed)]"
disabled={starting || confirmClose}
loading={starting}
onClick={() => void start()}
>
{t('cindyMake.upstream.personal')}
</Button>
</div>
)}
<ConfirmDialog
open={confirmClose}
onOpenChange={(open) => {
setConfirmClose(open);
if (!open)
requestAnimationFrame(() => closeButtonRef.current?.focus({ preventScroll: true }));
}}
title={t('cindyMake.preflight.closeTitle')}
description={t(`cindyMake.preflight.closeDescription.${closeStage}`)}
confirmText={t('cindyMake.preflight.closeConfirm')}
cancelText={t('cindyMake.preflight.keepOpen')}
zIndex={10002}
onConfirm={() => {
if (!submitting.current) onOpenChange(false);
}}
/>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}