diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index c82eb6a48a..1c25abac7f 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -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"; @@ -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); @@ -62,6 +63,8 @@ export function ChannelTimeline({ selectedGoal, showManagerTeamResults = false, onReviewGoalDraft, + onApplyGoalDraft, + goalDraftPreparationContext, onSuggestReply, onOpenGoalEvidence, onInterruptTurn, @@ -87,13 +90,25 @@ export function ChannelTimeline({ onSelect: (selection: WorkspaceDrawerSelection) => void; selectedGoal: WorkspaceGoal | null; showManagerTeamResults?: boolean; - onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onApplyGoalDraft?: (proposal: WorkspaceActionPreview) => Promise; + goalDraftPreparationContext?: string; onSuggestReply?: (text: string) => void; onOpenGoalEvidence?: (goalId: string) => void; onInterruptTurn?: (turnId: string) => Promise; onAdjustTurn?: (turnId: string) => void; }) { const { locale, t } = useWorkspaceI18n(); + const [draftProposalIds, setDraftProposalIds] = useState>({}); + 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(null); const timeline = useRef(null); @@ -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( @@ -176,7 +198,7 @@ export function ChannelTimeline({ ? t("timeline.runCompleted", { run: latestAnnounceable.run.title }) : ""; - const gatedItems = items.filter((item): item is Extract => + const gatedItems = presentedItems.filter((item): item is Extract => 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. @@ -197,7 +219,7 @@ export function ChannelTimeline({ ] as Array).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 => + const activeProposalItems = presentedItems.filter((item): item is Extract => 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 @@ -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) ? : null} {item.message.role === "assistant" && !item.message.pending && item.message.goalDraft - ? : null} + ? : null} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx index 692be830c2..b9ed7b90f5 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx @@ -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; + preparationContext?: string; + onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onApply?: (proposal: WorkspaceActionPreview) => Promise; onSuggest?: (text: string) => void; }) { - const { locale } = useWorkspaceI18n(); + const { locale, t } = useWorkspaceI18n(); const zh = locale === "zh-CN"; const pending = useRef(false); + const card = useRef(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; @@ -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
+ 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
{zh ? "目标草稿" : "Goal draft"}
{[ [zh ? "目标" : "Objective", draft.objective], [zh ? "完成标准" : "Completion criteria", draft.completion_criteria], [zh ? "执行边界" : "Execution boundary", draft.execution_boundary], ].map(([label, value]) =>
{label}
{value || (zh ? "待补充" : "Not specified")}
)}
+ {proposal ?
{proposal.fields.filter(field => field.key === "agent_id" || field.key === "workspace_ref") + .map(field =>
{field.label}
{field.value}
)}
: null} {draft.question ?

{draft.question}

: null} {onSuggest && draft.options.length ?
{draft.options.map(option => )} {zh ? "点选后可修改再发送,也可以直接输入。" : "Choose a reply to edit before sending, or type your own."}
: null} {error ?

{error}

: null} -
{zh ? "尚未创建或启动" : "Not created or started"} + {proposal?.gate ?

{proposal.gate.summary}

: null} + {proposal?.errorMessage ?

{proposal.reviewPlan + ? t(`actionReview.${proposal.reviewPlan.reason}`) : proposal.errorMessage}

: null} +
{onReview ? <> - {ready ? : null} - + {ready && !created ? : null} + {preparesCreation ? : } : null}
; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx index ad0cecaf4a..cae5df70fe 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx @@ -39,6 +39,7 @@ import { setupGoalChannel, stewardPrompts, transitionTypedAction, + listTypedActions, typedActionProposalSchema, type GoalRepositoryContext, type LarkGoalConnection, @@ -1030,6 +1031,7 @@ export function PersonalWorkspacePage({ const actionReadback = useTypedActionReadback(readOnly, selectedGoalId); const selectedAgentId = controlledAgentId ?? localAgentId; const goalAgentId = goalCreationAgentId(selectedAgentId, agents); + const goalDraftPreparations = useRef(new Map>()); // Only execution runtimes count: the read-only status projection answers // questions but runs nothing, and the loading placeholder is not a fact. const runtimeReadiness = useMemo(() => deriveRuntimeReadiness(agents @@ -1088,18 +1090,47 @@ export function PersonalWorkspacePage({ async function reviewGoalDraft(draft: GoalDraft, edit = false, draftId = "") { // Source message + reviewed contents survive retry without merging distinct requests. if (!edit && goalDraftReady(draft)) { - const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode( - JSON.stringify([draftId, draft, goalAgentId, locale]))); - const operationId = Array.from(new Uint8Array(bytes), value => value.toString(16).padStart(2, "0")).join(""); - await createPreview(goalCreateRequest({ objective: draft.objective, - completion: draft.completion_criteria, boundary: draft.execution_boundary, - permission: "read_only", agentId: goalAgentId, contextGoalId: null, operationId }, t)); - return; + // Keep existing locale-scoped operation ids compatible, but discover + // both languages so changing presentation cannot duplicate a Goal. + const operationIds = await Promise.all((["zh-CN", "en"] as const).map(async language => { + const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode( + JSON.stringify([draftId, draft, goalAgentId, language]))); + return Array.from(new Uint8Array(bytes), value => value.toString(16).padStart(2, "0")).join(""); + })); + const operationId = operationIds[locale === "zh-CN" ? 0 : 1]; + const preparationKey = JSON.stringify([selectionScope, draftId, draft, goalAgentId]); + const pendingPreparation = goalDraftPreparations.current.get(preparationKey); + if (pendingPreparation) return await pendingPreparation; + const preparation = (async () => { + // A reload or language change reads the original operation before + // preparing anything. Cached data cannot certify a failed read. + const readback = await listTypedActions({contextKind: "manager"}); + const recorded = readback.find(proposal => proposal.action_kind === "goal.create" + && operationIds.some(id => proposal.idempotency_key === `workspace-goal.create-${id}` + && proposal.normalized_parameters.goal_id === `goal-${id}`)); + if (recorded) return workspaceProposal(recorded, t); + return await createPreview(goalCreateRequest({ objective: draft.objective, + completion: draft.completion_criteria, boundary: draft.execution_boundary, + permission: "read_only", agentId: goalAgentId, contextGoalId: null, operationId }, t), { select: false }); + })(); + goalDraftPreparations.current.set(preparationKey, preparation); + try { return await preparation; } + finally { goalDraftPreparations.current.delete(preparationKey); } } setActionDraft({ kind: "goal", goalId: null, goalTitle: "", agentId: goalAgentId, text: draft.objective, completionCriteria: draft.completion_criteria, executionBoundary: draft.execution_boundary, permission: "read_only" }); } + async function confirmGoalDraft(proposal: WorkspaceActionPreview) { + if (readOnly) throw new Error(t("source.readOnlyWriteError")); + if (proposal.actionKind !== "goal.create") throw new Error(t("actionReview.targetChanged")); + const current = proposals[proposal.previewId] ?? proposal; + if (!current.reviewPlan?.canApply) { + setSelection({ item: current, kind: "proposal" }); + return current; + } + return await applyProposal(current, { presentation: "inline" }); + } function suggestReply(text: string) { setComposer(composer ? `${composer}\n${text}` : text); composerRef.current?.focus(); @@ -3025,7 +3056,7 @@ export function PersonalWorkspacePage({ run={activeSessionRun} /> ) : null} - callbacks.onCancelConversationPreparation!(selectedGoal.goalId) : undefined} @@ -3051,7 +3082,7 @@ export function PersonalWorkspacePage({ : (locale === "zh-CN" ? "正在读取原会话…" : "Reading the original conversation…"), description: "", } : workspaceTitle ? {title: workspaceTitle, description: t("workspace.empty")} : undefined} - onReviewGoalDraft={readOnly ? undefined : reviewGoalDraft} onSuggestReply={readOnly ? undefined : suggestReply} + goalDraftPreparationContext={`${goalAgentId}:${locale}`} onReviewGoalDraft={readOnly ? undefined : reviewGoalDraft} onApplyGoalDraft={readOnly ? undefined : confirmGoalDraft} onSuggestReply={readOnly ? undefined : suggestReply} items={selectedWorkspaceRef || originalConversation ? managerChatItems.filter((item) => item.kind === "message") : managerChatItems} onSelect={setSelection} selectedGoal={null} showManagerTeamResults={!selectedWorkspaceRef && !originalConversation} onAdjustTurn={steeringTurnId ? focusTurnComposer : undefined} diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 0dc3f77db4..4d9f6b7529 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -4142,3 +4142,30 @@ File/SQLite negative cases guard this boundary without changing valid activation complete D2/D5 closure, comparable full costs, V1–V5/V10, R1/M3 or C1 default cutover. The model reused its report generator between the two checks; these are not independent inference trials or an outcome/cost comparison. + +### 2026-11-15 — One confirmation for a complete conversational Goal draft + +- **Gap:** a complete draft skipped the form but still required a preview click + followed by drawer confirmation. The user could not see the resolved executor + and workspace until taking the first of those actions. +- **Delta:** the Dashboard prepares a visible complete draft's existing typed action, + displays its server-resolved Agent and workspace, and offers one explicit + `Create and start` confirmation. Incomplete drafts and read-only views cannot + prepare creation; Edit and typed availability/stale/recovery gates remain. + Existing locale-scoped operation identities are read before preparation; + reload, language changes and repeated clicks retain the original operation. + The visible draft owns one confirmation/recovery entry; the canonical proposal + stays available when its draft is not loaded. Collapsed unseen history does + not initiate preparation. +- **Evidence:** `goal-draft` covers preparation failure, no Goal writes before + confirmation, Edit/cancel, repeated clicks, reload, locale and narrow views. + `goal-draft-live` uses the real discovery and action store on isolated state + for resolved scope, lost-response readback, original-operation retry and + unavailable-Agent refusal. Its conversation is synthetic and its stub Agent + fails the first Turn; that failure is preserved rather than called success. +- **Boundary:** this is a V4/R1 entry increment using the existing Goal draft, + typed review/apply and creation/recovery owners. It adds no shared schema, + authority grant, alternate execution pipeline or C1 composition owner. + Full task-artifact success through this entry, installed native App/model + adoption, compaction retention, complete D2/D5 closure, comparable total cost, + V1–V5/V10, R1/M3 and C1 default cutover remain unqualified. diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md index 8bc670777d..f2e92e28d4 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -3220,3 +3220,22 @@ R1/M3、C1 切换和原目标回归仍未完成资格验证。 自然语言启动、原生 compaction 后的模型保留、渐进产品控制、完整 D2/D5 闭包、 可比完整成本、V1–V5/V10、R1/M3 或 C1 默认切换的资格验证。模型在两次检查 间复用了报告生成器;这些不是独立推理试验,也不是成果或成本对照实验。 + +### 2026-11-15 — 完整对话 Goal 草稿只需一次确认 + +- **缺口:**完整草稿已跳过表单,但仍需先点预览,再在抽屉确认。用户只有完成 + 这两步中的第一步后,才看得到服务解析的执行器和工作区。 +- **增量:**Dashboard 为可见的完整草稿准备既有 typed action,展示服务确认的 Agent 和 + 工作区,提供一次明确的“创建并开始”确认。未完整草稿与只读视图不能准备创建; + 修改入口以及 typed 可用性、陈旧和恢复 gate 保留。准备前先读取既有按语言生成 + 的操作身份;刷新、切换语言和重复点击复用原操作。 + 可见草稿保留一个确认和恢复入口;草稿未加载时,原 canonical proposal 仍可用。 + 尚未展开、不可见的历史不会发起准备。 +- **证据:**`goal-draft` 覆盖准备失败、确认前零 Goal 写入、修改与取消、重复 + 点击、刷新、语言和窄屏。`goal-draft-live` 在隔离状态使用真实 discovery 和 + action store,覆盖解析后的范围、丢失响应读回、原操作重试及 Agent 不可用拒绝。 + 对话是合成输入,stub Agent 的首轮执行失败;该失败保留,不记作成功。 +- **边界:**本次是 V4/R1 入口增量,复用既有 Goal 草稿、typed review/apply、 + 创建和恢复 owner。没有新增共享 schema、授权、替代执行管线或 C1 组合 owner。 + 通过该入口交付完整任务成果、已安装原生 App/模型采用、compaction 保留、完整 + D2/D5 闭包、可比总成本、V1–V5/V10、R1/M3 和 C1 默认切换仍未完成资格验证。 diff --git a/examples/personal-workspace-browser-smoke.mjs b/examples/personal-workspace-browser-smoke.mjs index 3bbfe65498..f15b4b49a9 100644 --- a/examples/personal-workspace-browser-smoke.mjs +++ b/examples/personal-workspace-browser-smoke.mjs @@ -107,6 +107,7 @@ import { goalShowcaseScenario } from "./personal-workspace-browser/goal-showcase import { stewardGroupTriggerScenario } from "./personal-workspace-browser/steward-group-trigger.mjs"; import { goalDraftScenario } from "./personal-workspace-browser/goal-draft.mjs"; +import { goalDraftLiveScenario } from "./personal-workspace-browser/goal-draft-live.mjs"; import { larkCliMissingScenario } from "./personal-workspace-browser/lark-cli-missing.mjs"; import { executionServiceOfflineScenario } from "./personal-workspace-browser/execution-service-offline.mjs"; @@ -164,6 +165,7 @@ scenarioCatalog.push(runtimeReadinessLiveScenario); scenarioCatalog.push(attentionNotificationsScenario); scenarioCatalog.push(attentionNotificationsLiveScenario); scenarioCatalog.push(firstGoalHomeLiveScenario); +scenarioCatalog.push(goalDraftLiveScenario); scenarioCatalog.push(goalSuggestionsScenario); scenarioCatalog.push(goalSuggestionsLiveScenario); scenarioCatalog.push(managedAgentSessionsScenario); diff --git a/examples/personal-workspace-browser/fixture.mjs b/examples/personal-workspace-browser/fixture.mjs index 1b84b840e8..54fb211d85 100644 --- a/examples/personal-workspace-browser/fixture.mjs +++ b/examples/personal-workspace-browser/fixture.mjs @@ -2113,6 +2113,7 @@ export async function installApi(page, { fixturePort = port, goalSubagentConfigu const storedProposal = actionProposals.get(apply[1]); const proposal = { schema_version: "loopx_chat_action_proposal_v1", proposal_id: apply[1], action_kind: actionKind, + idempotency_key: storedProposal?.idempotency_key, summary: actionKind === "team.plan" && storedProposal ? storedProposal.summary : "已应用", normalized_parameters: actionKind === "team.plan" && storedProposal ? storedProposal.normalized_parameters : preview?.normalized_parameters ?? storedProposal?.normalized_parameters ?? {}, diff --git a/examples/personal-workspace-browser/goal-draft-live.mjs b/examples/personal-workspace-browser/goal-draft-live.mjs new file mode 100644 index 0000000000..c43d728d17 --- /dev/null +++ b/examples/personal-workspace-browser/goal-draft-live.mjs @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {once} from "node:events"; +import {mkdtemp, readFile, stat} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join, resolve} from "node:path"; +import {createInterface} from "node:readline"; +import {resolveTestPython} from "../../scripts/test-python.mjs"; +import {waitForHttp} from "../dashboard-browser-smoke-support.mjs"; +import {outputDir, repoRoot} from "./fixture.mjs"; +import {fetchWorkspaceBackend, openWorkspacePage} from "./scenario-context.mjs"; + +// Conversation delivery is synthetic. Discovery, preview, apply and recovery +// use the real Chat owner on disposable state. The stub Agent's failed first +// Turn must never be presented as completed work. +export const goalDraftLiveScenario = { + id: "goal-draft-live", requiresBackendReadback: true, + async run({browser, collectCoverage, url}) { + const coverageEntries = []; + for (const available of [true, false]) { + const root = await mkdtemp(join(tmpdir(), "loopx-goal-draft-live-")); + const child = spawn(resolveTestPython({repoRoot}), ["-u", + resolve(repoRoot, "examples/personal-workspace-browser/fresh-install-backend.py"), + root, ...(available ? [] : ["--no-agent"])], {cwd: repoRoot, + env: {...process.env, PYTHONPATH: repoRoot, LOOPX_USAGE_PING: "0"}, stdio: ["ignore", "pipe", "pipe"]}); + const closed = once(child, "close"), lines = createInterface({input: child.stdout}); + let session, diagnostics = "", loseApplyResponse = available; + const previews = [], applies = []; + child.stderr.on("data", chunk => {diagnostics = (diagnostics + chunk).slice(-4000);}); + try { + const ready = await Promise.race([once(lines, "line").then(([line]) => JSON.parse(line)), + closed.then(() => {throw new Error(`fresh backend exited: ${diagnostics}`);})]); + const backend = `http://127.0.0.1:${ready.port}`; + await waitForHttp(`${backend}/status.json?view=workspace-directory`); + const registry = join(ready.project, ".loopx/registry.json"); + const draft = {objective: "Prepare the release checklist", completion_criteria: "A checklist with validation steps", + execution_boundary: "Read project files only", question: "", options: []}; + session = await openWorkspacePage(browser, url, {collectCoverage, beforeGoto: async (api, page) => { + api.answerForMessage = () => ({message: "The goal is ready to review.", goal_draft: draft}); + // Keep the synthetic conversation runtime distinct from the real + // action executor catalog (which preview validates independently). + const paths = new Set(["/status.json", "/api/chat/projects"]); + await page.route(target => paths.has(target.pathname) || target.pathname.startsWith("/api/actions"), async route => { + const request = route.request(), pathname = new URL(request.url()).pathname; + if (pathname === "/api/actions/preview") previews.push(request.postDataJSON()); + if (pathname.endsWith("/apply")) applies.push(pathname); + try { + const response = await fetchWorkspaceBackend(route, backend); + if (pathname.endsWith("/apply") && loseApplyResponse) {loseApplyResponse = false; await route.abort("failed");} + else await route.fulfill({response}); + } catch {await route.abort().catch(() => {});} + }); + }}); + const {page} = session; + await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: "对话", exact: true}).click(); + await page.locator(".personal-channel-composer textarea").fill(draft.objective); + await page.getByRole("button", {name: "发送", exact: true}).click(); + const card = page.getByRole("region", {name: "目标草稿"}).last(); + await card.waitFor(); + if (!available) { + await card.getByRole("alert").filter({hasText: /Agent 当前不可用/}).waitFor(); + await assert.rejects(stat(registry), {code: "ENOENT"}); + assert.equal(applies.length, 0, "An unavailable Agent never receives apply"); + await card.getByRole("button", {name: "查看并处理", exact: true}).click(); + await page.locator(".personal-context-drawer").waitFor({state: "visible"}); + await assert.rejects(stat(registry), {code: "ENOENT"}); + } else { + const create = card.getByRole("button", {name: "创建并开始", exact: true}); + await create.waitFor(); + assert.equal(await page.locator('.personal-proposal-row[data-action-kind="goal.create"]').count(), 0); + await card.getByText(/^默认:project/).waitFor(); + assert.ok(!(await card.innerText()).includes(root), "The resolved scope is public safe"); + await assert.rejects(stat(registry), {code: "ENOENT"}); + assert.equal(applies.length, 0, "Preparation never applies a Goal"); + await page.screenshot({path: resolve(outputDir, "goal-draft-live-ready.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await card.scrollIntoViewIfNeeded(); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + await page.screenshot({path: resolve(outputDir, "goal-draft-live-ready-narrow.png"), animations: "disabled"}); + await create.evaluate(button => {button.click(); button.click();}); + await card.getByRole("button", {name: "重试创建", exact: true}).waitFor({timeout: 60_000}); + const first = JSON.parse(await readFile(registry, "utf8")); + assert.equal(first.goals.length, 1); + const proposalId = applies[0].split("/").at(-2); + const original = (await (await fetch(`${backend}/api/actions/${proposalId}`)).json()).proposal; + assert.equal(original.normalized_parameters.goal_id, first.goals[0].id); + assert.equal(original.normalized_parameters.heartbeat.enabled, false); + assert.equal(original.normalized_parameters.permission, "read_only"); + assert.notEqual(original.status, "applied", "A failed first Turn is not completed creation"); + assert.equal(await card.getByRole("button", {name: "已创建", exact: true}).count(), 0); + assert.equal(applies.length, 1, "Repeated clicks apply once even when the response is lost"); + await page.reload({waitUntil: "networkidle"}); + await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: "对话", exact: true}).click(); + await card.getByRole("button", {name: "重试创建", exact: true}).click(); + await card.getByRole("button", {name: "重试创建", exact: true}).waitFor({timeout: 60_000}); + assert.deepEqual(applies, [applies[0], applies[0]], "Recovery retries the original operation"); + assert.equal(previews.length, 1, "Reload reads the original preview"); + assert.deepEqual(JSON.parse(await readFile(registry, "utf8")).goals.map(goal => goal.id), [first.goals[0].id]); + await page.screenshot({path: resolve(outputDir, "goal-draft-live-recovery.png"), animations: "disabled"}); + } + coverageEntries.push(...await session.close()); + } catch (error) { + await session?.page.screenshot({path: resolve(outputDir, "goal-draft-live-failed.png")}).catch(() => {}); + const body = await session?.page.locator("body").innerText().catch(() => ""); + await session?.close().catch(() => {}); + throw new Error(`${error.message}; body=${body?.slice(-6000)}; backend=${diagnostics}`); + } finally { + lines.close(); + if (child.exitCode === null && child.signalCode === null) { + child.kill("SIGTERM"); + const kill = setTimeout(() => child.kill("SIGKILL"), 5000); + try {await closed;} finally {clearTimeout(kill);} + } + } + } + return {coverageEntries, backendReadbackVerified: true, note: "Synthetic conversation, real discovery/actions: prepare without Goal writes, one confirmation, lost-response readback, original retry and one registry Goal; unavailable Agent writes nothing; stub first-Turn failure stays explicit."}; + }, +}; diff --git a/examples/personal-workspace-browser/goal-draft.mjs b/examples/personal-workspace-browser/goal-draft.mjs index 69402a06d6..1054c665de 100644 --- a/examples/personal-workspace-browser/goal-draft.mjs +++ b/examples/personal-workspace-browser/goal-draft.mjs @@ -31,11 +31,24 @@ export const goalDraftScenario = { assert.equal(api.turnRequests.length, requests, "Suggestion auto-sent a request"); assert.equal(api.actionPreviews.length, 0); assert.equal(api.durableWriteCount, writes); + api.failNextActionPreview = true; await send("重点比较资本支出,列出来源"); await card.getByText("重点比较资本支出,列出来源", {exact: true}).waitFor(); + await card.scrollIntoViewIfNeeded(); + await card.getByRole("alert").waitFor(); + assert.equal(api.durableWriteCount, writes, "Preparing a complete draft cannot create a Goal"); + await card.getByRole("button", {name: "重新准备", exact: true}).click(); + await card.getByRole("button", {name: "创建并开始", exact: true}).waitFor(); + assert.equal(await page.locator('.personal-proposal-row[data-action-kind="goal.create"]').count(), 0, + "The visible draft owns one confirmation instead of a duplicate action card"); + await card.getByText("codex", {exact: true}).waitFor(); + const requestKey = api.actionPreviews.at(-1).idempotency_key; + const preparedCount = api.actionPreviews.length; await page.reload({waitUntil: "networkidle"}); await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); await card.getByText("重点比较资本支出,列出来源", {exact: true}).waitFor(); + await card.getByRole("button", {name: "创建并开始", exact: true}).waitFor(); + assert.equal(api.actionPreviews.length, preparedCount, "Reload reads the existing operation"); await card.getByRole("button", {name: "修改", exact: true}).click(); const form = page.getByRole("dialog", {name: "创建新 Goal"}); assert.equal(await form.getByLabel("目标", {exact: true}).inputValue(), draft.objective); @@ -76,25 +89,32 @@ export const goalDraftScenario = { assert.equal(api.durableWriteCount, writes, "Cancelling the reviewed draft mutated state"); await page.setViewportSize({width: 1512, height: 982}); const beforePreview = api.actionPreviews.length; - await card.getByRole("button", {name: "预览创建", exact: true}).click(); - await page.getByText("确认执行", {exact: true}).waitFor(); assert.equal(await form.count(), 0, "Complete draft should skip the redundant form"); - assert.equal(api.actionPreviews.length, beforePreview + 1); - assert.equal(api.actionPreviews.at(-1).normalized_parameters.workspace_ref, "current"); - assert.equal(api.actionPreviews.at(-1).normalized_parameters.completion_criteria, "重点比较资本支出,列出来源"); - assert.equal(api.actionPreviews.at(-1).normalized_parameters.permission, "read_only"); - assert.equal(api.actionPreviews.at(-1).normalized_parameters.heartbeat.enabled, false); - const requestKey = api.actionPreviews.at(-1).idempotency_key; - await page.getByRole("button", {name: "关闭", exact: true}).click(); + const preparedPreview = api.actionPreviews.find(item => item.idempotency_key === requestKey); + assert.equal(preparedPreview.normalized_parameters.workspace_ref, "current"); + assert.equal(preparedPreview.normalized_parameters.completion_criteria, "重点比较资本支出,列出来源"); + assert.equal(preparedPreview.normalized_parameters.permission, "read_only"); + assert.equal(preparedPreview.normalized_parameters.heartbeat.enabled, false); await page.reload({waitUntil: "networkidle"}); await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); - await card.getByRole("button", {name: "预览创建", exact: true}).click(); - await page.getByText("确认执行", {exact: true}).waitFor(); - assert.equal(api.actionPreviews.at(-1).idempotency_key, requestKey, "Reopening must preserve operation identity"); - await page.getByRole("button", {name: "创建 Goal 并开始首轮", exact: true}).last().click(); - await page.getByText("已应用,LoopX 状态将刷新。", {exact: true}).first().waitFor(); + const create = card.getByRole("button", {name: "创建并开始", exact: true}); + await create.waitFor(); + await card.scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(outputDir, "goal-draft-ready.png"), animations: "disabled"}); + await create.evaluate(button => { button.click(); button.click(); }); + await card.getByRole("button", {name: "已创建", exact: true}).waitFor(); + assert.equal(api.actionPreviews.length, beforePreview, "Confirmation uses the prepared operation"); + assert.equal(await page.locator(".personal-context-drawer").count(), 0, "Ordinary creation needs one inline confirmation"); assert.equal(api.durableWriteCount, writes + 1); assert.equal(api.actionApplies.length, 1); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "en")); + await page.reload({waitUntil: "networkidle"}); + await page.getByRole("navigation", {name: "Manager view"}).getByRole("button", {name: "Chat", exact: true}).click(); + await page.getByRole("region", {name: "Goal draft"}).last().getByRole("button", {name: "Created", exact: true}).waitFor(); + assert.equal(api.actionPreviews.length, beforePreview, "Language changes do not create another operation"); + assert.equal(api.actionApplies.length, 1); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + await page.reload({waitUntil: "networkidle"}); await page.keyboard.press("Escape"); await page.locator(".personal-goal-link").first().click(); await page.getByRole("navigation", {name: "Goal 视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); @@ -108,8 +128,8 @@ export const goalDraftScenario = { await englishCard.getByRole("button", {name: "Refine goal"}).waitFor(); await englishCard.scrollIntoViewIfNeeded(); await page.screenshot({path: resolve(outputDir, "goal-draft-english.png"), animations: "disabled"}); - assert.deepEqual(errors, []); - return {coverageEntries: await close(), note: "Goal draft suggestions require explicit send; corrections and reload preserve draft; existing Goal preview retains read-only and disabled heartbeat defaults."}; + assert.deepEqual(errors, ["Failed to load resource: the server responded with a status of 503 (Service Unavailable)"]); + return {coverageEntries: await close(), note: "Suggestions require explicit send; complete drafts prepare without writes and offer one confirmation; preparation failure is retryable; reload and locale preserve identity; repeated clicks apply once; Edit, narrow view and read-only/disabled heartbeat defaults remain."}; } catch(error) { await page.screenshot({path: resolve(outputDir, "goal-draft-failed.png")}); const text = await page.locator("body").innerText();