Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {ContextHelp} from "./context-help";
import {ArrowRight, ChevronDown, Circle, CircleAlert, CircleCheck, CircleHelp, Clock, Hand, Info, List, Play, Plus, Search} from "lucide-react";
import {useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
import {Component, createRef, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode} from "react";
import type {GoalWorkDisplayClass, GoalWorkspaceDigest} from "../../../../../../loopx/control_plane/presentation/goal_workspace_digest.js";
import type {WorkspaceActionPreview, WorkspaceActionPreviewRequest, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceModel, WorkspaceTimelineItem} from "./personal-workspace-model";
import {localizedSessionStatus, useWorkspaceI18n} from "./i18n";
Expand Down Expand Up @@ -223,7 +223,7 @@ export function GoalWorkspaceWork({goal, digest, items, userTodos, selectedTodoI
</div> : null}
{!readOnly ? <AddTask goal={goal} proposals={proposals} onPreview={onPreview} onSelect={select}/> : null}
</header>
<div className="goal-owner-groups" hidden={lens !== "owner"}>{digest.work.groups.map(group => <section className="goal-owner-group" key={group.ownerId ?? ""} data-owner-id={group.ownerId ?? ""}>
<OwnerWorkGroups hidden={lens !== "owner"}>{digest.work.groups.map(group => <section className="goal-owner-group" key={group.ownerId ?? ""} data-owner-id={group.ownerId ?? ""}>
<header><h3>{ownerName(group.ownerId)}</h3><span>{group.todoIds.length} {zh ? "项任务" : "tasks"} · {group.todoIds.filter(id => rows.get(id)?.displayClass === group.displayClass).length} {goalWorkClassLabel(group.displayClass, zh)}</span>
{!readOnly && group.ownerId && onOpenAgentConversation ? <button type="button" className="goal-owner-conversation" data-agent-id={group.ownerId} aria-label={zh ? `与 ${ownerName(group.ownerId)} 对话` : `Talk to ${ownerName(group.ownerId)}`} onClick={() => onOpenAgentConversation(group.ownerId!)}>{zh ? "工作记录" : "Work conversation"}</button> : null}
</header>
Expand All @@ -233,7 +233,7 @@ export function GoalWorkspaceWork({goal, digest, items, userTodos, selectedTodoI
{group.todoIds.slice(3).map(id => task(id))}
</RemainingWork> : null}
</section>)}
</div>
</OwnerWorkGroups>
{visited.has("board") || lens === "board" ? <div hidden={lens !== "board"}>{board}</div> : null}
{visited.has("map") || lens === "map" ? <div hidden={lens !== "map"}>{map}</div> : null}
</section>
Expand All @@ -254,6 +254,35 @@ export function GoalWorkspaceWork({goal, digest, items, userTodos, selectedTodoI
</div>;
}

type OwnerWorkGroupsProps = {hidden: boolean; children: ReactNode};

class OwnerWorkGroups extends Component<OwnerWorkGroupsProps, object, string | null> {
private readonly groups = createRef<HTMLDivElement>();

getSnapshotBeforeUpdate(): string | null {
const groups = this.groups.current;
const focused = groups?.ownerDocument.activeElement;
return focused instanceof HTMLButtonElement && groups?.contains(focused)
? focused.dataset.todoId ?? null : null;
}

componentDidUpdate(_previousProps: OwnerWorkGroupsProps, _previousState: object, todoId: string | null) {
// Crossing the summary boundary replaces the button. Restore its focus if
// the browser dropped it during this commit and the same task is still here.
const groups = this.groups.current;
if (!todoId || !groups || groups.closest("[hidden]") || groups.ownerDocument.activeElement !== groups.ownerDocument.body) return;
const row = groups.querySelector<HTMLButtonElement>(`button[data-todo-id="${CSS.escape(todoId)}"]`);
if (!row) return;
const disclosure = row.closest<HTMLDetailsElement>("details.goal-work-more");
if (disclosure) disclosure.open = true;
row.focus();
}

render() {
return <div className="goal-owner-groups" hidden={this.props.hidden} ref={this.groups}>{this.props.children}</div>;
}
}

function RemainingWork({selectedTodoId, label, children}: {selectedTodoId: string | null; label: string; children: ReactNode}) {
const disclosure = useRef<HTMLDetailsElement>(null);
useEffect(() => {if (selectedTodoId && disclosure.current) disclosure.current.open = true;}, [selectedTodoId]);
Expand Down
26 changes: 26 additions & 0 deletions docs/product/runtimes/codex-cli/codex-cli-automation-driver.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,32 @@ and `--host-adapter-command-json ...` for a compatible Trae or
another CLI after its wrapper implements the typed stdin/stdout contract in the
host-neutral protocol.

The built-in Codex result schema accepts `validated_completion` for a fully
delivered selected Todo. After independent validation, the adapter invokes the
existing Todo lifecycle, including its controller-declared validator, before
accountable refresh and one quota debit. It retains the original launch lease
generation in the Turn journal for completion and cached-result recovery;
lease loss or a newer same-Agent generation cannot authorize the old result.
`validated_progress` remains partial progress and never silently completes work.
For a predeclared terminal Todo, closeout after debit uses the original
completion receipt and closes the same Turn.
Goal acceptance remains a separate owner check.

After independent validation, the adapter checks the original Goal's running
authority before settling either result. When the owner stops the Goal during
that validation, the Turn retains its validation checkpoint and leaves the
Todo and quota untouched.

内置 Codex 的结果格式支持 `validated_completion`,用于已满足全部要求的已选 Todo。
独立验证通过后,adapter 先调用现有 Todo 生命周期及 controller 声明的完成验证器,
再写回可核算进展并扣额一次。Turn journal 保留启动时的原租约代次,完成和缓存结果
恢复都使用该代次;租约丢失或同 Agent 的新代次不能授权旧结果。`validated_progress`
仍表示部分进展,不会被静默升级为完成。对于预声明的终态 Todo,扣额后按原完成回执
收尾同一轮 Turn。Goal 验收仍由原 owner 单独检查。

独立验证结束后,adapter 会在结算前重新检查原 Goal 的运行权限。验证期间若 owner
停止 Goal,Turn 保留验证记录,Todo 和额度不变。

That wrapper is deliberately thin: it translates one Turn request into one
bounded Agent CLI invocation, preserves only an opaque local resume handle, and
returns one typed candidate result. LoopX remains responsible for the control
Expand Down
22 changes: 22 additions & 0 deletions docs/reference/canonical-todo-completion-update.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,28 @@ Python 只复用 OS I/O;准入、声明、期限、源/租约见证和完成

## Linked User completion effects

### Monitor observations and User gates

A Monitor observation and a User gate completion have different identities and
different owners. An observation is evidence: a file appearing, a changed hash or
a successful external job never completes or approves a User gate, and the
Monitor contract projects no gate completion command. When a due Monitor is
admitted while the agent has open User gates, its actions carry a read-only
notice instead.

Two attempts stay rejected by their existing owners: completing the gate with
the Monitor Turn (`settlement binding does not match the original quota
guard`), and attaching evidence through a plain `todo update`
(`handoff_mode_requires_lease`). The agent records the observation with
`quota monitor-poll` and yields. An observation is not tied to any gate, so it is
not reported as one. The gate owner completes a gate through the User lifecycle
with their own decision; a linked target then resumes for a fresh guarded Turn.

Work that may continue on an observed change without an owner decision does not
belong behind a User gate. Emit it from the observation itself with
`quota monitor-poll --material-change --next-agent-todo ...`: the successor is an
independent runnable Agent Todo, admitted by its own fresh guard.

An admitted `todo complete --decision-outcome approve|reject|cancel` now commits
its exact linked Agent Todo effects in the **same** provider transaction as the
User completion and receipt. Ordinary User actions completed through update or
Expand Down
35 changes: 35 additions & 0 deletions examples/personal-workspace-browser/goal-workspace-m2.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ async function runM2Pass({browser, collectCoverage, url}) {
const renderBudget = {coverageEnabled:collectCoverage,initialMs,expandMs,switchMs,switchSamplesMs,...lensBudget,
longTaskSupported,switchLongTasks,nodeCount:200};
console.log(JSON.stringify({m2RenderBudget:renderBudget}));
await verifyFocusAfterReprioritization(page, now, many[4]);
assert.equal(writes.length,0,`Rendering created effects: ${writes}`);
assert.equal(session.errors.length,0,session.errors.join('\n'));
if (!collectCoverage) assert.ok(lensBudget.withinBudget, `Loaded lens switches exceeded repeated 1s target or 2s ceiling: ${JSON.stringify({switchSamplesMs,...lensBudget})}`);
Expand All @@ -295,6 +296,40 @@ async function runM2Pass({browser, collectCoverage, url}) {
finally {await session.close();}
}

async function verifyFocusAfterReprioritization(page, now, todo) {
const byOwner = now.getByRole("button", {name:"按负责人", exact:true});
await byOwner.click();
const owner = now.locator('.goal-owner-group[data-owner-id="worker-0"]');
const remaining = owner.locator(".goal-work-more");
await remaining.locator(":scope > summary").press("Enter");
assert.equal(await remaining.evaluate(node => node.open), false);

const row = `[data-todo-id="${todo.todo_id}"]`;
const leading = owner.locator(`:scope > ${row}`);
const moved = remaining.locator(`${row}[data-work-class="blocked"]`);
const refresh = page.getByRole("button", {name:"刷新状态", exact:true});
// Simulate a status refresh while the keyboard user remains on the page.
const refreshWithoutMovingFocus = () => refresh.evaluate(button => button.click());

await byOwner.focus();
todo.status = "blocked";
await refreshWithoutMovingFocus();
await moved.waitFor({state:"attached"});
assert.equal(await moved.isVisible(), false, "An unfocused task does not open its disclosure on refresh");
assert.equal(await byOwner.evaluate(node => document.activeElement === node), true, "Refresh leaves focus outside the task list alone");

todo.status = "open";
await refreshWithoutMovingFocus();
await leading.focus();
todo.status = "blocked";
await refreshWithoutMovingFocus();
await moved.waitFor({state:"attached"});
assert.equal(await moved.evaluate(node => document.activeElement === node), true, "The same task keeps keyboard focus after it moves");
await page.keyboard.press("Enter");
await page.waitForURL(value => value.searchParams.get("todo") === todo.todo_id);
await page.locator(".personal-context-drawer").waitFor();
}


async function verifyRemoteSelection(browser, url) {
const snapshot = JSON.parse(await readFile(resolve(repoRoot,"examples/status.example.json"),"utf8"));
Expand Down
38 changes: 37 additions & 1 deletion loopx/cli_commands/turn_run_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from functools import partial
import sys as _sys
from collections.abc import Callable, Mapping
from contextlib import contextmanager, nullcontext
from pathlib import Path
from typing import TYPE_CHECKING as _TYPE_CHECKING
from typing import Any
Expand Down Expand Up @@ -476,8 +477,29 @@ def terminal_closeout(
effect_ref: str,
) -> dict[str, object]:
require_effect_ref(effect_ref, SettlementStepKind.TERMINAL_CLOSEOUT)
if args.host == "codex-cli":
# Builtin completion has already retired the original lease.
# Verify the exact terminal receipt; never start another completion.
observed = terminal_closeout_resolver(effect_ref)
receipt = observed.get("payload")
if observed.get("kind") == "committed" and isinstance(receipt, dict):
return receipt
return {
"ok": False,
"appended": False,
"reason": observed.get("reason") or "Builtin terminal completion receipt is missing",
}
return todo_completion(result, effect_ref=effect_ref)

def codex_writeback(
result: dict[str, object], *, effect_ref: str,
) -> dict[str, object]:
# Accountable refresh requires durable controller validation even for
# a predeclared terminal Todo. Other hosts keep their existing order.
if result.get("result_kind") == "validated_completion":
return completion_writeback(result, effect_ref=effect_ref)
return writeback(result, effect_ref=effect_ref)

def current_status() -> dict[str, object]:
return collect_turn_status_payload(
args,
Expand Down Expand Up @@ -847,6 +869,19 @@ def settlement_admission():
return request_settlement_lifetime(request_locator, settlement_identity,
registry_path=registry_path, runtime_root=runtime_root, workspace=project)

if args.host == "codex-cli" and goal_admission is not None:
request_lifetime = settlement_admission or nullcontext

@contextmanager
def codex_settlement_admission():
with request_lifetime():
# Independent validation can outlive the running Goal.
# Check the original authority before any settlement effect.
goal_admission.require_running(operation="codex_cli_turn_settle")
yield

settlement_admission = codex_settlement_admission

def on_managed_start_admitted() -> None:
if settlement_identity.request_subject is not None:
require_current_request_operation(request_locator, settlement_identity,
Expand Down Expand Up @@ -898,7 +933,8 @@ def on_managed_start_admitted() -> None:
retry_failed=bool(args.retry_failed_turn),
task_validator=task_validator,
settlement_admission=settlement_admission,
writeback=writeback if args.execute else None,
writeback=(codex_writeback if args.host == "codex-cli" else writeback)
if args.execute else None,
completion_writeback=completion_writeback if args.execute else None,
completion_intent=completion_intent if args.execute else None,
terminal_closeout=terminal_closeout if args.execute else None,
Expand Down
45 changes: 41 additions & 4 deletions loopx/control_plane/quota/accounting_artifact_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,13 +508,35 @@ export function resolveQuotaAccountingEffect(
return { kind: "absent" };
}

function spendIdentityMismatch(index: JsonObject, retained: JsonObject): boolean {
// The spend writers retain these bindings even before commit metadata was
// introduced. Missing historical fields are unknown; explicit conflicts are
// never authenticated by a matching timestamp or billing terms.
return ["agent_id", "effect_ref", "turn_instance_id", "todo_id",
"replan_obligation_id", "settlement_identity", "goal_ref"].some(field => {
const expected = index[field], actual = retained[field];
return expected !== undefined && expected !== null && expected !== "" &&
actual !== undefined && actual !== null && actual !== "" &&
canonicalJson(expected) !== canonicalJson(actual);
});
}

export async function readQuotaSpendEventFromRun(
runsDir: string,
run: JsonObject,
goalId: string,
): Promise<JsonObject | null> {
const contract = contractFor("spend");
const indexCommit = run[contract.metadataField];
const inline = jsonObject(run.quota_event);
if (inline) return inline;
if (inline && indexCommit === undefined) {
if (spendIdentityMismatch(run, inline)) {
throw new EffectRuntimeRequestError(
"quota spend JSON artifact identity does not match its index row",
);
}
return inline;
}
if (typeof run.json_path !== "string" || !run.json_path.trim()) return null;
let targetPath: string;
try {
Expand Down Expand Up @@ -550,15 +572,30 @@ export async function readQuotaSpendEventFromRun(
throw new EffectRuntimeRequestError("quota spend JSON artifact is malformed");
}
const record = requiredObject(value, "quota spend JSON artifact");
const artifactCommit = jsonObject(record[contract.metadataField]);
// The writer repeats its commit identity in the index and artifact. An
// in-directory file can still describe a different debit for the same Goal.
const commitMismatch = indexCommit !== undefined && (
jsonObject(indexCommit) === null || artifactCommit === null ||
canonicalJson(indexCommit) !== canonicalJson(artifactCommit)
);
// A historical row without a commit reference can still have an explicit
// Run timestamp. Preserve omitted historical fields, but reject conflicts.
const timestampMismatch = typeof run.generated_at === "string" && run.generated_at !== "" &&
typeof record.generated_at === "string" && record.generated_at !== "" &&
run.generated_at !== record.generated_at;
const event = jsonObject(record.quota_event);
if (
record.classification !== contractFor("spend").classification ||
(record.goal_id !== undefined && record.goal_id !== goalId)
record.classification !== contract.classification ||
(record.goal_id !== undefined && record.goal_id !== goalId) ||
commitMismatch || timestampMismatch || spendIdentityMismatch(run, record) ||
(event !== null && spendIdentityMismatch(run, event))
) {
throw new EffectRuntimeRequestError(
"quota spend JSON artifact identity does not match its index row",
);
}
return jsonObject(record.quota_event);
return event;
}

export async function lookupQuotaAccountingReplay(
Expand Down
Loading
Loading