Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {DocumentAttachment, isDocumentAttachment} from "./document-attachment";
import { MessageActivity } from "./message-activity";
import { GoalDraftCard } from "./goal-draft-card";
import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js";
import {goalDraftReady} from "./goal-create-request";
import {Fragment, useEffect, useEffectEvent, useLayoutEffect, useRef, useState} from "react";
import { CollaborationCards } from "./collaboration-card";
import {ConversationReplyContext} from "./conversation-requests";
Expand All @@ -20,7 +21,7 @@ import {ManagerTeamResult} from "./manager-team-result";
import { compareProposalRecency } from "./proposal-recency";
import { conversationOrder } from "./conversation-order";
import { ConversationFind, conversationMessageKey } from "./conversation-find";
import type { WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model";
import type { WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model";

function answerLink(sessionId: string, messageId: string) {
const url = new URL(window.location.href);
Expand Down Expand Up @@ -62,6 +63,8 @@ export function ChannelTimeline({
selectedGoal,
showManagerTeamResults = false,
onReviewGoalDraft,
onApplyGoalDraft,
goalDraftPreparationContext,
onSuggestReply,
onOpenGoalEvidence,
onInterruptTurn,
Expand All @@ -87,13 +90,25 @@ export function ChannelTimeline({
onSelect: (selection: WorkspaceDrawerSelection) => void;
selectedGoal: WorkspaceGoal | null;
showManagerTeamResults?: boolean;
onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise<void>;
onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise<WorkspaceActionPreview | void>;
onApplyGoalDraft?: (proposal: WorkspaceActionPreview) => Promise<WorkspaceActionPreview>;
goalDraftPreparationContext?: string;
onSuggestReply?: (text: string) => void;
onOpenGoalEvidence?: (goalId: string) => void;
onInterruptTurn?: (turnId: string) => Promise<void>;
onAdjustTurn?: (turnId: string) => void;
}) {
const { locale, t } = useWorkspaceI18n();
const [draftProposalIds, setDraftProposalIds] = useState<Record<string, string>>({});
const draftKey = (id: string, draft: GoalDraft) => JSON.stringify([id, draft, goalDraftPreparationContext]);
const inlineProposalIds = new Set(items.flatMap(item => item.kind === "message"
&& item.message.goalDraft && goalDraftReady(item.message.goalDraft)
? [draftProposalIds[draftKey(`${item.message.sourceSessionId ?? ""}:${item.message.id}`, item.message.goalDraft)]] : []));
async function reviewDraft(draft: GoalDraft, edit = false, id = "") {
const result = await onReviewGoalDraft?.(draft, edit, id);
if (!edit && result) setDraftProposalIds(current => ({...current, [draftKey(id, draft)]: result.previewId}));
return result;
}
const [findNavigation, setFindNavigation] = useState(0);
const [findMessageId, setFindMessageId] = useState<string | null>(null);
const timeline = useRef<HTMLDivElement>(null);
Expand All @@ -108,7 +123,14 @@ export function ChannelTimeline({
});
return () => cancelAnimationFrame(frame);
}, [findMessageId, findNavigation]);
const orderedItems = conversationOrder(items.filter(item => {
const presentedItems = items.filter(item => {
// The visible draft already owns this confirmation and recovery entry.
// Its canonical proposal remains available when the draft is not loaded.
if (item.kind === "proposal" && !readOnly && onApplyGoalDraft && onReviewGoalDraft
&& inlineProposalIds.has(item.proposal.previewId)) return false;
return true;
});
const orderedItems = conversationOrder(presentedItems.filter(item => {
if (item.kind !== "message") return true;
if (item.message.queued) return false;
const queued = item.message.role === "user" && queuedTurnKeys?.has(
Expand Down Expand Up @@ -176,7 +198,7 @@ export function ChannelTimeline({
? t("timeline.runCompleted", { run: latestAnnounceable.run.title })
: "";

const gatedItems = items.filter((item): item is Extract<WorkspaceTimelineItem, { kind: "proposal" }> =>
const gatedItems = presentedItems.filter((item): item is Extract<WorkspaceTimelineItem, { kind: "proposal" }> =>
item.kind === "proposal" && item.proposal.status === "gated" && item.proposal.actionKind !== "operation.execute");
// Only routine execution is folded. Waiting, interruption, and failures stay
// visible; no prose-based inference that a waiting run is safe to ignore.
Expand All @@ -197,7 +219,7 @@ export function ChannelTimeline({
] as Array<string | number | null>).concat(locale === "zh-CN"
? [workingCount && `${workingCount} 个执行中`, queuedCount && `${queuedCount} 个排队中`, completedCount && `${completedCount} 次执行已结束`, progressCount && `${progressCount} 项进展更新`]
: [workingCount && `${workingCount} running`, queuedCount && `${queuedCount} queued`, completedCount && `${completedCount} runs finished`, progressCount && `${progressCount} progress updates`]).filter(Boolean).join(" · ");
const activeProposalItems = items.filter((item): item is Extract<WorkspaceTimelineItem, { kind: "proposal" }> =>
const activeProposalItems = presentedItems.filter((item): item is Extract<WorkspaceTimelineItem, { kind: "proposal" }> =>
item.kind === "proposal" && (item.proposal.status !== "gated" || item.proposal.actionKind === "operation.execute"));
// Only drafts awaiting the owner fold behind the newest one; applying, applied and failed results stay visible.
// "Newest" is read from the stored proposal, not from the position in this
Expand Down Expand Up @@ -273,7 +295,7 @@ export function ChannelTimeline({
: null}
{item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? <MessageActivity message={item.message} onCancelPreparation={onCancelPreparation} onInterruptTurn={onInterruptTurn} onAdjustTurn={onAdjustTurn}/> : null}
{item.message.role === "assistant" && !item.message.pending && item.message.goalDraft
? <GoalDraftCard draftId={`${item.message.sourceSessionId ?? ""}:${item.message.id}`} draft={item.message.goalDraft} onReview={onReviewGoalDraft} onSuggest={onSuggestReply}/> : null}
? <GoalDraftCard draftId={`${item.message.sourceSessionId ?? ""}:${item.message.id}`} preparationContext={goalDraftPreparationContext} draft={item.message.goalDraft} onReview={onReviewGoalDraft ? reviewDraft : undefined} onApply={onApplyGoalDraft} onSuggest={onSuggestReply}/> : null}
<CollaborationCards request={item.message.collaboration} requests={item.message.collaborations} />
</div>
</article>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,59 @@
import { useRef, useState } from "react";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js";
import type { WorkspaceActionPreview } from "./personal-workspace-model";
import {goalDraftReady} from "./goal-create-request";
import { useWorkspaceI18n } from "./i18n";
import "./goal-draft-card.css";

export function GoalDraftCard({ draft, draftId, onReview, onSuggest }: {
export function GoalDraftCard({ draft, draftId, preparationContext = "", onReview, onApply, onSuggest }: {
draft: GoalDraft;
draftId: string;
onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise<void>;
preparationContext?: string;
onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise<WorkspaceActionPreview | void>;
onApply?: (proposal: WorkspaceActionPreview) => Promise<WorkspaceActionPreview>;
onSuggest?: (text: string) => void;
}) {
const { locale } = useWorkspaceI18n();
const { locale, t } = useWorkspaceI18n();
const zh = locale === "zh-CN";
const pending = useRef(false);
const card = useRef<HTMLElement>(null);
const [visible, setVisible] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [prepared, setPrepared] = useState<{ key: string; proposal: WorkspaceActionPreview }>();
const [preparing, setPreparing] = useState(false);
const [preparationAttempt, setPreparationAttempt] = useState(0);
const ready = goalDraftReady(draft);
const draftKey = JSON.stringify([draftId, draft, preparationContext]);
const proposal = prepared?.key === draftKey ? prepared.proposal : undefined;
const prepare = useEffectEvent(async () => onReview?.(draft, false, draftId));
const preparesCreation = ready && visible && Boolean(onReview && onApply);
useEffect(() => {
if (visible || !card.current) return;
const observer = new IntersectionObserver(([entry]) => {
if (!entry?.isIntersecting) return;
observer.disconnect();
setVisible(true);
}, {root: card.current.closest(".personal-channel-scroll")});
observer.observe(card.current);
return () => observer.disconnect();
}, [visible]);
useEffect(() => {
let current = true;
setPrepared(undefined);
setError("");
if (!preparesCreation) { setPreparing(false); return; }
setPreparing(true);
void prepare().then(result => {
if (!current) return;
if (result?.actionKind === "goal.create") setPrepared({ key: draftKey, proposal: result });
else setError(zh ? "无法准备创建,请重试。" : "Could not prepare creation. Please retry.");
}).catch(failure => {
if (current) setError(failure instanceof Error ? failure.message : String(failure));
}).finally(() => { if (current) setPreparing(false); });
return () => { current = false; };
}, [draftKey, preparesCreation, preparationAttempt]);
const created = proposal?.status === "applied" && proposal.reviewPlan?.interaction === "completed";
async function review(edit = false) {
if (!onReview || pending.current) return;
pending.current = true;
Expand All @@ -25,23 +63,45 @@ export function GoalDraftCard({ draft, draftId, onReview, onSuggest }: {
catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
finally { pending.current = false; setBusy(false); }
}
return <section className="personal-goal-draft" aria-label={zh ? "目标草稿" : "Goal draft"}>
async function create() {
if (!onApply || pending.current) return;
if (!proposal) { setPreparationAttempt(attempt => attempt + 1); return; }
pending.current = true;
setBusy(true);
setError("");
try {
const result = await onApply(proposal);
setPrepared(current => current?.key === draftKey ? { key: draftKey, proposal: result } : current);
}
catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
finally { pending.current = false; setBusy(false); }
}
return <section ref={card} className="personal-goal-draft" aria-label={zh ? "目标草稿" : "Goal draft"}>
<strong>{zh ? "目标草稿" : "Goal draft"}</strong>
<dl>{[
[zh ? "目标" : "Objective", draft.objective],
[zh ? "完成标准" : "Completion criteria", draft.completion_criteria],
[zh ? "执行边界" : "Execution boundary", draft.execution_boundary],
].map(([label, value]) => <div key={label}><dt>{label}</dt><dd>{value || (zh ? "待补充" : "Not specified")}</dd></div>)}</dl>
{proposal ? <dl>{proposal.fields.filter(field => field.key === "agent_id" || field.key === "workspace_ref")
.map(field => <div key={field.key}><dt>{field.label}</dt><dd>{field.value}</dd></div>)}</dl> : null}
{draft.question ? <p>{draft.question}</p> : null}
{onSuggest && draft.options.length ? <div className="personal-goal-draft-options">
{draft.options.map(option => <button type="button" key={option} onClick={() => onSuggest(option)}>{option}</button>)}
<small>{zh ? "点选后可修改再发送,也可以直接输入。" : "Choose a reply to edit before sending, or type your own."}</small>
</div> : null}
{error ? <p role="alert">{error}</p> : null}
<footer><span>{zh ? "尚未创建或启动" : "Not created or started"}</span>
{proposal?.gate ? <p role="alert">{proposal.gate.summary}</p> : null}
{proposal?.errorMessage ? <p role="alert">{proposal.reviewPlan
? t(`actionReview.${proposal.reviewPlan.reason}`) : proposal.errorMessage}</p> : null}
<footer>
{onReview ? <>
{ready ? <button type="button" disabled={busy} onClick={() => void review(true)}>{zh ? "修改" : "Edit"}</button> : null}
<button type="button" disabled={busy} onClick={() => void review()}>{busy ? (zh ? "正在准备…" : "Preparing…") : ready ? (zh ? "预览创建" : "Preview creation") : (zh ? "补充目标" : "Refine goal")}</button>
{ready && !created ? <button type="button" disabled={busy} onClick={() => void review(true)}>{zh ? "修改" : "Edit"}</button> : null}
{preparesCreation ? <button type="button" disabled={busy || preparing || created} onClick={() => void create()}>
{created ? (zh ? "已创建" : "Created") : busy || preparing ? (zh ? "正在准备…" : "Preparing…")
: !proposal ? (zh ? "重新准备" : "Retry preparation") : proposal.reviewPlan?.canApply ? proposal.status === "error" ? (zh ? "重试创建" : "Retry creation")
: (zh ? "创建并开始" : "Create and start") : (zh ? "查看并处理" : "Review and resolve")}
</button> : <button type="button" disabled={busy} onClick={() => void review()}>{busy ? (zh ? "正在准备…" : "Preparing…") : ready ? (zh ? "预览创建" : "Preview creation") : (zh ? "补充目标" : "Refine goal")}</button>}
</> : null}
</footer>
</section>;
Expand Down
Loading
Loading