Skip to content
Open
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 @@ -21,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 { WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model";
import type { PersonalWorkspaceCallbacks, WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model";

function answerLink(sessionId: string, messageId: string, turnId?: string) {
const url = new URL(window.location.href);
Expand Down Expand Up @@ -68,7 +68,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({
onApplyGoalDraft,
goalDraftPreparationContext,
onSuggestReply,
onOpenGoalEvidence,
onOpenGoalChat,
onInterruptTurn,
onAdjustTurn,
onCancelPreparation,
Expand Down Expand Up @@ -96,7 +96,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({
onApplyGoalDraft?: (proposal: WorkspaceActionPreview) => Promise<WorkspaceActionPreview>;
goalDraftPreparationContext?: string;
onSuggestReply?: (text: string) => void;
onOpenGoalEvidence?: (goalId: string) => void;
onOpenGoalChat?: PersonalWorkspaceCallbacks["onOpenGoal"];
onInterruptTurn?: (turnId: string) => Promise<void>;
onAdjustTurn?: (turnId: string) => void;
}) {
Expand Down Expand Up @@ -258,9 +258,9 @@ export const ChannelTimeline = memo(function ChannelTimeline({
<b>{taskReceipt ? t("feedback.taskStartRequested")
: item.proposal.status === "gated" && item.proposal.actionKind !== "operation.execute" ? t("timeline.review")
: item.proposal.primaryLabel ?? t("timeline.reviewAndConfirm")}</b>
</button>{showManagerTeamResults && onOpenGoalEvidence && appliedTeamPlan
</button>{showManagerTeamResults && onOpenGoalChat && appliedTeamPlan
&& item.proposal.goalId && item.proposal.teamPlanTodoIds?.length
? <ManagerTeamResult goalId={item.proposal.goalId} todoIds={item.proposal.teamPlanTodoIds} zh={locale === "zh-CN"} onOpenGoalEvidence={onOpenGoalEvidence}/>
? <ManagerTeamResult goalId={item.proposal.goalId} todoIds={item.proposal.teamPlanTodoIds} zh={locale === "zh-CN"} onOpenGoalEvidence={onOpenGoalChat}/>
: null}</Fragment>
);
}
Expand Down Expand Up @@ -295,7 +295,7 @@ export const ChannelTimeline = memo(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}`} preparationContext={goalDraftPreparationContext} draft={item.message.goalDraft} onReview={onReviewGoalDraft ? reviewDraft : undefined} onApply={onApplyGoalDraft} onSuggest={onSuggestReply}/> : null}
? <GoalDraftCard draftId={`${item.message.sourceSessionId ?? ""}:${item.message.id}`} preparationContext={goalDraftPreparationContext} draft={item.message.goalDraft} onReview={onReviewGoalDraft ? reviewDraft : undefined} onApply={onApplyGoalDraft} onOpenGoalChat={onOpenGoalChat} 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,17 +1,18 @@
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 type { PersonalWorkspaceCallbacks, WorkspaceActionPreview } from "./personal-workspace-model";
import {goalDraftReady} from "./goal-create-request";
import {GoalCreationExecution} from "./goal-creation-execution";
import { useWorkspaceI18n } from "./i18n";
import "./goal-draft-card.css";

export function GoalDraftCard({ draft, draftId, preparationContext = "", onReview, onApply, onSuggest }: {
export function GoalDraftCard({ draft, draftId, preparationContext = "", onReview, onApply, onOpenGoalChat, onSuggest }: {
draft: GoalDraft;
draftId: string;
preparationContext?: string;
onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise<WorkspaceActionPreview | void>;
onApply?: (proposal: WorkspaceActionPreview) => Promise<WorkspaceActionPreview>;
onOpenGoalChat?: PersonalWorkspaceCallbacks["onOpenGoal"];
onSuggest?: (text: string) => void;
}) {
const { locale, t } = useWorkspaceI18n();
Expand Down Expand Up @@ -55,6 +56,7 @@ export function GoalDraftCard({ draft, draftId, preparationContext = "", onRevie
return () => { current = false; };
}, [draftKey, preparesCreation, preparationAttempt]);
const created = proposal?.status === "applied" && proposal.reviewPlan?.interaction === "completed";
const firstSession = created ? proposal.createdManagedSession?.target : undefined;
async function review(edit = false) {
if (!onReview || pending.current) return;
pending.current = true;
Expand Down Expand Up @@ -99,7 +101,9 @@ export function GoalDraftCard({ draft, draftId, preparationContext = "", onRevie
<footer>
{onReview ? <>
{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()}>
{firstSession && onOpenGoalChat ? <button type="button" onClick={() => void onOpenGoalChat(firstSession.goalId, firstSession)}>
{zh ? "打开首轮对话" : "Open first conversation"}
</button> : 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")
: proposal.reviewPlan.creationExecution ? (zh ? "创建并开始" : "Create and start") : (zh ? "创建" : "Create")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,7 @@ const en = {
"drawer.recoverEditResult": "Recover operation result",
"drawer.retryOriginal": "Retry original operation",
"actionReview.canonical_update_retry": "The edit is not yet verified. Retry this operation to recover its result.",
"actionReview.goal_creation_retry": "Goal initialization is incomplete. Retry the original creation; its recorded storage choice is preserved.",
"actionReview.goal_creation_retry": "Goal setup is incomplete. Retry in the same workspace to continue from the last saved step.",
"actionReview.task_start_retry": "The Task was saved. Retry its original start to continue with that Task.",
"actionReview.todo_creation_retry": "Confirmation submitted. Retry to recover the original result.",
"actionReview.canonical_update_projection_pending": "The operation was committed; display delivery is pending. Retry this operation to restore the current view.",
Expand Down Expand Up @@ -2614,7 +2614,7 @@ const zhCN: Record<WorkspaceMessageKey, string> = {
"drawer.recoverEditResult": "恢复操作结果",
"drawer.retryOriginal": "重试原操作",
"actionReview.canonical_update_retry": "编辑结果尚未确认。重试此操作以恢复原结果。",
"actionReview.goal_creation_retry": "Goal 初始化尚未完成。请重试原创建操作,已记录的存储选择会保留。",
"actionReview.goal_creation_retry": "Goal 初始化尚未完成。重试后将在原工作区从已保存的步骤继续。",
"actionReview.task_start_retry": "任务已保存。重试原操作以继续启动这个任务。",
"actionReview.todo_creation_retry": "已提交创建确认。重试本次确认以取回结果。",
"actionReview.canonical_update_projection_pending": "操作已提交,展示尚未同步。重试此操作以恢复当前视图。",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1448,7 +1448,7 @@ export function PersonalWorkspacePage({
adjust: focusTurnComposer,
cancel: canCancelTimelineTurn ? () => callbacks.onCancelConversationPreparation?.(timelineActionTarget) : undefined,
interrupt: canInterruptTimelineTurn ? (turnId: string) => callbacks.onInterruptConversationTurn?.(timelineActionTarget, turnId) : undefined,
openEvidence: (goalId: string) => { selectGoal(goalId, "chat"); },
openGoalChat: (goalId: string, target?: ManagedConversationTarget) => { selectGoal(goalId, "chat", target); },
};
useLayoutEffect(() => { currentTimelineActions.current = nextTimelineActions; });
const timelineActions = useMemo(() => {
Expand All @@ -1465,7 +1465,7 @@ export function PersonalWorkspacePage({
onAdjustTurn: (turnId: string) => current()?.adjust(turnId),
onCancelPreparation: () => current()?.cancel?.(),
onInterruptTurn: async (turnId: string) => { await current()?.interrupt?.(turnId); },
onOpenGoalEvidence: (goalId: string) => current()?.openEvidence(goalId),
onOpenGoalChat: (goalId: string, target?: ManagedConversationTarget) => current()?.openGoalChat(goalId, target),
};
}, [timelineKey, goalDraftTargetChanged]);
const conversationOpen = (!agentWorkActive || managedWorkActive) && (selectedGoal ? selectedGoalTab === "chat" : managerChatOpen);
Expand Down Expand Up @@ -3137,6 +3137,7 @@ export function PersonalWorkspacePage({
onReviewGoalDraft={readOnly ? undefined : timelineActions.onReviewGoalDraft}
onApplyGoalDraft={readOnly ? undefined : timelineActions.onApplyGoalDraft}
onSuggestReply={readOnly ? undefined : timelineActions.onSuggestReply}
onOpenGoalChat={timelineActions.onOpenGoalChat}
items={visibleTimelineItems} onSelect={timelineActions.onSelect} selectedGoal={selectedGoal}
onAdjustTurn={steeringTurnId ? timelineActions.onAdjustTurn : undefined}
onCancelPreparation={canCancelTimelineTurn ? timelineActions.onCancelPreparation : undefined}
Expand All @@ -3161,7 +3162,7 @@ export function PersonalWorkspacePage({
onAdjustTurn={steeringTurnId ? timelineActions.onAdjustTurn : undefined}
onCancelPreparation={canCancelTimelineTurn ? timelineActions.onCancelPreparation : undefined}
onInterruptTurn={canInterruptTimelineTurn ? timelineActions.onInterruptTurn : undefined}
onOpenGoalEvidence={timelineActions.onOpenGoalEvidence} />
onOpenGoalChat={timelineActions.onOpenGoalChat} />
))}
</> : null}
</div>
Expand Down
22 changes: 21 additions & 1 deletion examples/personal-workspace-browser/first-goal-home-live.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,34 @@ export const firstGoalHomeLiveScenario = {
await drawer.getByText("新 Goal · 待你确认", { exact: true }).waitFor({ state: "visible", timeout: 20_000 });
// The snapshot readback completes shortly after the card appears; a stale-card notice must not remain.
await drawer.getByText("提案状态刷新失败", { exact: false }).waitFor({ state: "hidden", timeout: 15_000 });
const isApplyResponse = (response) => response.request().method() === "POST" && /^\/api\/actions\/[^/]+\/apply$/.test(new URL(response.url()).pathname);
const firstApply = page.waitForResponse(isApplyResponse);
await drawer.locator(".personal-primary-action").click();
const applyButton = drawer.getByRole("button", { name: "确认并应用", exact: true });
if (await applyButton.count()) await applyButton.click();
await drawer.getByText("新 Goal · 出错", { exact: true }).waitFor({ state: "visible", timeout: 60_000 });
const outcome = (await drawer.innerText()).replace(/\s+/g, " ");
assert.match(outcome, /Goal 初始化尚未完成/, `the service names what is not finished: ${outcome.slice(0, 300)}`);
assert.match(outcome, /Goal ID: goal-[0-9a-f-]+ · 已应用/, "the Goal itself was registered before the first Turn failed");
assert.ok(await drawer.getByRole("button", { name: "重试原操作", exact: true }).count(), "the original operation can be retried");
const applyPath = new URL((await firstApply).url()).pathname;
const proposalUrl = backend + applyPath.slice(0, -"/apply".length);
const readSteps = async () => {
const response = await fetch(proposalUrl);
assert.ok(response.ok, "the original proposal can be read back");
return (await response.json()).proposal.checkpoint.steps;
};
const before = await readSteps();
assert.equal(before.todos_created.todo_ids.length, 1);
assert.equal(before.first_turn_started, undefined);
const [retried] = await Promise.all([
page.waitForResponse(isApplyResponse),
drawer.getByRole("button", { name: "重试原操作", exact: true }).click(),
]);
assert.equal(new URL(retried.url()).pathname, applyPath, "retry applies the original proposal");
const afterRetry = await readSteps();
assert.equal(afterRetry.goal_bootstrapped.goal_id, before.goal_bootstrapped.goal_id);
assert.deepEqual(afterRetry.todos_created.todo_ids, before.todos_created.todo_ids);
assert.equal(afterRetry.first_turn_started, undefined, "the unavailable Agent still has no started Turn");
await page.screenshot({ path: resolve(outputDir, "first-goal-home-live-applied.png"), animations: "disabled" });

// The real service now has a registry with exactly this Goal, and the
Expand Down
2 changes: 1 addition & 1 deletion examples/personal-workspace-browser/typed-actions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ export const typedActionsScenario = {

await page.locator(".personal-proposal-row", {hasText: "Storage recovery"}).click();
const creationRecovery = page.locator('.personal-context-drawer[data-context-kind="proposal"]');
await creationRecovery.getByText("Goal 初始化尚未完成。请重试原创建操作,已记录的存储选择会保留。", {exact: true}).waitFor();
await creationRecovery.getByText("Goal 初始化尚未完成。重试后将在原工作区从已保存的步骤继续。", {exact: true}).waitFor();
if ((await creationRecovery.innerText()).includes("没有写入任何变更")) throw new Error("Partial creation claimed no writes");
await page.setViewportSize({width: 390, height: 844});
const creationRetry = creationRecovery.getByRole("button", {name: "重试原操作", exact: true});
Expand Down
12 changes: 7 additions & 5 deletions loopx/chat_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -740,11 +740,6 @@ def require_first_turn_readback(turn: Mapping[str, object]) -> None:
raise conflict
elif current_fingerprint != proposal.get("expected_state_fingerprint"):
return self._stale_proposal(proposal_id, current_fingerprint)
self._agent_eligibility(
str(parameters.get("agent_id") or "codex"),
project=project,
require_healthy=parameters.get("open_session") is not False,
)
self.store.save_checkpoint(
proposal_id,
step="workspace_validated",
Expand All @@ -754,6 +749,13 @@ def require_first_turn_readback(turn: Mapping[str, object]) -> None:
"workspace_digest": workspace_digest,
},
)
# The workspace is already verified. Keep its identity if the Agent
# goes offline between preview and confirmation.
self._agent_eligibility(
str(parameters.get("agent_id") or "codex"),
project=project,
require_healthy=parameters.get("open_session") is not False,
)
runtime_root = resolve_runtime_root(
self._registry(), self.runtime_root_override, registry_path=self.registry_path
).resolve()
Expand Down
20 changes: 19 additions & 1 deletion tests/test_chat_goal_workspace_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def test_first_goal_preview_refuses_an_unavailable_agent_as_a_typed_gate(tmp_pat
server.registry_path, server.runtime_root, server.runtime_root_override = registry, runtime, str(runtime)
server.action_store = ChatActionStore(runtime / "chat/actions")
server.action_service = ChatActionService(store=server.action_store, registry_path=registry,
chat_store=sessions, runtime_controller=controller, workspace_roots=[project])
chat_store=sessions, runtime_controller=controller, workspace_roots=[project], runtime_root_override=runtime)
server.chat_store, server.runtime_controller, server.verbose = sessions, controller, False
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
Expand Down Expand Up @@ -449,6 +449,24 @@ def request(path, body=None):
catalog["rows"] = []
status, hosted_unregistered = request("/api/actions/preview", hosted)
assert status == 409 and hosted_unregistered["gate"]["registered"] is False

# Losing the endpoint after preview keeps the checked workspace, but
# creates no Goal. Restoring it can finish the same confirmation.
proposal_id = previewed["proposal"]["proposal_id"]
apply_path = f"/api/actions/{proposal_id}/apply"
status, _ = request(apply_path, {})
assert status >= 400
failed = next(row for row in request("/api/actions")[1]["proposals"] if row["proposal_id"] == proposal_id)
assert failed["status"] == "failed"
assert set(failed["checkpoint"]["steps"]) == {"workspace_validated"}
assert json.loads(registry.read_text())["goals"] == []

catalog["rows"] = [{"agent_id": "codex", "available": True, "tool_calls": True, "trust_scope": "read_only"}]
status, recovered = request(apply_path, {})
assert status == 202, recovered
assert recovered["proposal"]["proposal_id"] == proposal_id
assert recovered["proposal"]["receipt"]["resource_ids"]["goal_id"] == "goal-first"
assert [goal["id"] for goal in json.loads(registry.read_text())["goals"]] == ["goal-first"]
finally:
server.shutdown()
thread.join(timeout=5)
Expand Down
Loading