Skip to content

Commit f2f1810

Browse files
authored
Merge pull request #8727 from loopx-project/codex/audit-chat-display-recovery-pr-20261114
Keep interrupted Todo and Monitor confirmations recoverable in Chat
2 parents 81efc95 + c1aeaf3 commit f2f1810

20 files changed

Lines changed: 1240 additions & 100 deletions

‎apps/presentation/dashboard/smoke/todo-confirmation-browser-smoke.mjs‎

Lines changed: 143 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,120 @@ async function verifyMonitorSignalScopeProjection({page, post, origin, width, pr
318318
console.log(provider + " " + width + "px: monitor.create & monitor.update cards show applied, preserved_current (incl. PR filter & reopen), and retryable unverified scope");
319319
}
320320

321+
async function goalTab(page, label) {
322+
const tab = page.getByRole("navigation", {name: /Goal view|Goal 视图/})
323+
.getByRole("button", {name: label});
324+
const goal = page.locator(".personal-goal-link:visible").first();
325+
const nav = page.locator(".personal-mobile-menu:visible").first();
326+
await tab.or(goal).or(nav).first().waitFor();
327+
if (!await tab.isVisible()) {
328+
if (await nav.isVisible()) await nav.click();
329+
await goal.click();
330+
}
331+
await tab.click();
332+
}
333+
334+
async function verifyPendingDisplay({page, post, origin, width, provider, snapshot, fixture = "/__confirmation_fixture/display"}) {
335+
await post(fixture, {hold: true});
336+
const original = await snapshot();
337+
const titles = width === 390
338+
? ["核对欠付项的责任人与跟进记录", "保留交接文档中的原始验收证据"]
339+
: ["Review follow-up owners in the release checklist", "Preserve evidence for the support handover after release"];
340+
const operations = [];
341+
for (let i = 0; i < titles.length; i++) {
342+
const [created, preview] = await post("/api/actions/preview", {
343+
action_kind: "todo.create", context: {kind: "goal", goal_id: "goal-a"},
344+
normalized_parameters: {goal_id: "goal-a", text: titles[i]}, summary: "Create task",
345+
idempotency_key: "display-confirmation-" + width + "-" + i,
346+
});
347+
assert.equal(created, 201, JSON.stringify(preview));
348+
const id = preview.proposal.proposal_id;
349+
const path = "/api/actions/" + id;
350+
const [, pending] = await post(path + "/apply");
351+
assert.equal(pending.proposal.failure.error_code, "canonical_create_projection_pending");
352+
const createdStep = pending.proposal.checkpoint.steps.todo_created;
353+
assert.equal(createdStep.projection_delivery, "pending");
354+
operations.push({id, path, title: titles[i], todo: createdStep.todo_id, receipt: createdStep.canonical_receipt.receipt_id});
355+
assert.equal((await post(path + "/cancel"))[0], 409);
356+
}
357+
const committed = await snapshot();
358+
assert.equal(committed.ids.length, original.ids.length + 2);
359+
assert.notEqual(operations[0].todo, operations[1].todo);
360+
await page.goto(origin + "/chat/?goal=goal-a");
361+
await goalTab(page, /^(Overview|概览)$/);
362+
await page.reload();
363+
await goalTab(page, /^(Overview|概览)$/);
364+
const overview = page.getByRole("region", {name: /Display updates pending|展示待更新/});
365+
await overview.waitFor();
366+
for (const {title} of operations) await overview.getByRole("button", {name: title, exact: true}).waitFor();
367+
await page.screenshot({path: resolve(output, provider + "-" + width + "-display-overview.png")});
368+
await goalTab(page, /^(Chat|对话)$/);
369+
const cards = page.locator(".personal-proposal-row[data-action-kind='todo.create']");
370+
const card = title => cards.filter({hasText: title});
371+
// As with ordinary confirmations, these two persisted records have the
372+
// same action title. Both must remain selectable without first doing IO.
373+
for (const {title} of operations) await card(title).waitFor();
374+
await page.screenshot({path: resolve(output, provider + "-" + width + "-display-chat.png")});
375+
const [earlier, later] = operations;
376+
await card(later.title).click();
377+
const retry = page.getByRole("dialog").getByRole("button", {name: /^(Retry original operation|重试原操作)$/});
378+
await retry.waitFor();
379+
// Replace the upstream reply after apply ran. File finishes display, while
380+
// SQLite keeps it pending. Both temporarily lose the two readback routes.
381+
await post(fixture, {hold: provider === "sqlite", gateway_reply: later.id, hold_list: true, hold_detail: true});
382+
const gateway = page.waitForResponse(response => response.url().endsWith(later.path + "/apply"));
383+
const unavailable = [later.path, "/api/actions"].map(path => page.waitForResponse(response =>
384+
response.request().method() === "GET" && new URL(response.url()).pathname === path && response.status() === 503));
385+
await retry.click();
386+
const [reply] = await Promise.all([gateway, ...unavailable]);
387+
assert.equal(reply.status(), 502);
388+
assert.match(reply.headers()["content-type"], /^text\/html\b/);
389+
await retry.waitFor();
390+
assert.ok(await retry.isEnabled());
391+
assert.equal(await page.getByRole("dialog").getByRole("button", {name: /regenerate|重新生成/i}).count(), 0);
392+
await page.screenshot({path: resolve(output, provider + "-" + width + "-gateway-recovery.png")});
393+
await post(fixture, {hold: false, hold_list: false, hold_detail: false});
394+
function checkReceipt(proposal, operation) {
395+
assert.equal(proposal.proposal_id, operation.id);
396+
assert.equal(proposal.receipt.receipt_id, operation.receipt);
397+
assert.equal(proposal.receipt.resource_ids.todo_id, operation.todo);
398+
assert.equal(proposal.receipt.projection_verified, true);
399+
}
400+
async function recover(operation) {
401+
const outcome = page.waitForResponse(response => response.url().endsWith(operation.path + "/apply"));
402+
await retry.click();
403+
const response = await outcome;
404+
assert.equal(response.status(), 200);
405+
checkReceipt((await response.json()).proposal, operation);
406+
await page.keyboard.press("Escape");
407+
}
408+
const observed = (await (await fetch(origin + later.path)).json()).proposal;
409+
if (provider === "sqlite") {
410+
assert.equal(observed.failure.error_code, "canonical_create_projection_pending");
411+
assert.equal(observed.checkpoint.steps.todo_created.canonical_receipt.receipt_id, later.receipt);
412+
} else {
413+
checkReceipt(observed, later);
414+
}
415+
await recover(later);
416+
await goalTab(page, /^(Overview|概览)$/);
417+
await overview.getByRole("button", {name: earlier.title, exact: true}).click();
418+
// A connection drop with the list unavailable still uses exact readback.
419+
await post(fixture, {drop_reply: earlier.id, hold_list: true});
420+
const disconnected = page.waitForEvent("requestfailed", {
421+
predicate: request => request.method() === "POST" && request.url().endsWith(earlier.path + "/apply"),
422+
});
423+
await retry.click();
424+
await disconnected;
425+
await page.getByRole("dialog").getByRole("button", {name: /^(View updated Goal|查看更新后的 Goal)$/}).waitFor();
426+
const exact = await fetch(origin + earlier.path);
427+
checkReceipt((await exact.json()).proposal, earlier);
428+
await post(fixture, {hold_list: false});
429+
await page.keyboard.press("Escape");
430+
await overview.waitFor({state: "hidden"});
431+
assert.deepEqual(await snapshot(), committed);
432+
console.log(provider + " " + width + "px: HTML 502 and two failed reads keep the original retry; both receipts recovered");
433+
}
434+
321435
async function verify(provider, interruptedStep) {
322436
const child = spawn(resolveTestPython({repoRoot: root}),
323437
["-u", fileURLToPath(new URL("todo-confirmation-http-fixture.py", import.meta.url)), provider, assetDir, interruptedStep],
@@ -366,16 +480,7 @@ async function verify(provider, interruptedStep) {
366480
});
367481
await page.goto(origin + "/chat/?goal=goal-a");
368482
async function openConfirmation() {
369-
const chat = page.getByRole("navigation", {name: /Goal view|Goal 视图/})
370-
.getByRole("button", {name: /^(Chat|对话)$/});
371-
const goal = page.locator(".personal-goal-link:visible").first();
372-
const nav = page.locator(".personal-mobile-menu:visible").first();
373-
await chat.or(goal).or(nav).first().waitFor();
374-
if (!await chat.isVisible()) {
375-
if (await nav.isVisible()) await nav.click();
376-
await goal.click();
377-
}
378-
await chat.click();
483+
await goalTab(page, /^(Chat|对话)$/);
379484
const card = page.locator(".personal-proposal-row").filter({hasText: text});
380485
await card.first().click();
381486
}
@@ -448,6 +553,7 @@ async function verify(provider, interruptedStep) {
448553
await page.screenshot({path: resolve(output, capturePrefix + "-" + width + "-result.png")});
449554
console.log(provider + " " + width + "px: " + interruptedStep + "; original proposal and one Todo write across reload");
450555
if (!beforeWrite) {
556+
await verifyPendingDisplay({page, post, origin, width, provider, snapshot});
451557
await verifyMonitorSignalScopeProjection({page, post, origin, width, provider, snapshot});
452558
}
453559
} catch (error) {
@@ -471,6 +577,33 @@ async function verify(provider, interruptedStep) {
471577
assert.equal(created, 201);
472578
assert.equal(successor.proposal.regenerated_from, preview.proposal_id);
473579
assert.notEqual(successor.proposal.proposal_id, preview.proposal_id);
580+
if (interruptedStep === "todo_created") {
581+
const display = "/__confirmation_fixture/display";
582+
const [previewCode, monitor] = await post("/api/actions/preview", {
583+
action_kind: "monitor.create", context: {kind: "goal", goal_id: "goal-a"},
584+
normalized_parameters: {goal_id: "goal-a", agent_id: "agent-a", target: "Review release readiness",
585+
target_key: "release-readiness", cadence: "2h", timezone: "UTC", stop_condition: "watch_only"},
586+
summary: "Review release readiness", idempotency_key: "monitor-display-recovery",
587+
});
588+
assert.equal(previewCode, 201);
589+
const monitorPath = "/api/actions/" + monitor.proposal.proposal_id;
590+
const original = await snapshot();
591+
await post(display, {hold: true});
592+
const [, pending] = await post(monitorPath + "/apply");
593+
const saved = pending.proposal.checkpoint.steps.todo_created;
594+
assert.equal(pending.proposal.failure.error_code, "canonical_create_projection_pending");
595+
const committed = await snapshot();
596+
assert.deepEqual(committed.ids, [...original.ids, saved.todo_id].sort());
597+
assert.equal((await post(monitorPath + "/cancel"))[0], 409);
598+
assert.deepEqual(await snapshot(), committed);
599+
await post(display, {hold: false});
600+
const [applied, recovered] = await post(monitorPath + "/apply");
601+
assert.equal(applied, 200);
602+
assert.equal(recovered.proposal.receipt.resource_ids.todo_id, saved.todo_id);
603+
assert.equal(recovered.proposal.receipt.projection_verified, true);
604+
assert.deepEqual(await snapshot(), committed);
605+
console.log(provider + ": the Monitor cancel returns 409 and the original confirmation recovers its display");
606+
}
474607
} finally {
475608
child.kill("SIGINT");
476609
await exited;

‎apps/presentation/dashboard/smoke/todo-confirmation-http-fixture.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from pathlib import Path
44
import json
5+
import socket
56
import sys
67
from tempfile import TemporaryDirectory
78

@@ -24,6 +25,7 @@ def main(provider, assets_dir, interrupted_step):
2425
from loopx.chat_action_store import ChatActionStore
2526
from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
2627
from loopx.control_plane.effect_runtime import restart_effect_runtime
28+
from loopx.control_plane.todos import provider_projection
2729
from loopx.control_plane.todos.mutation_api import add_goal_todo
2830

2931
with TemporaryDirectory(prefix="loopx-confirmation-fixture-") as directory, pytest.MonkeyPatch.context() as patch:
@@ -33,6 +35,8 @@ def main(provider, assets_dir, interrupted_step):
3335
lost = {}
3436
interrupted = set()
3537
controls = {"skip_interrupt": False, "fail_scope_write": False, "unverified_scope": False}
38+
display = {"hold": False, "drop_reply": None, "gateway_reply": None, "hold_list": False, "hold_detail": False}
39+
write_state = provider_projection.atomic_write_state_text
3640
checkpoint = ChatActionStore.save_checkpoint
3741
write_scope_file = steward_monitor_scope._write_steward_monitor_scope_file
3842
check_todo_commit = todo_creation.check_canonical_todo_commit_current
@@ -46,13 +50,18 @@ def interrupt(self, proposal_id, *, step, receipt, **kwargs):
4650
if interrupted_step == "applying" and step == "todo_create_prepared" and proposal_id not in interrupted:
4751
interrupted.add(proposal_id)
4852
raise InterruptedConfirmation()
49-
if step == interrupted_step and proposal_id not in interrupted:
53+
if step == interrupted_step and proposal_id not in interrupted and not display["hold"]:
5054
interrupted.add(proposal_id)
5155
if step == "todo_created":
5256
lost[proposal_id] = receipt["canonical_receipt"]
5357
raise OSError("test: first create checkpoint write interrupted")
5458
return checkpoint(self, proposal_id, step=step, receipt=receipt, **kwargs)
5559

60+
def render(path, text, **kwargs):
61+
if display["hold"]:
62+
raise PermissionError("test: display disabled after authority commits")
63+
return write_state(path, text, **kwargs)
64+
5665
def guarded_scope_write(*args, **kwargs):
5766
if controls["fail_scope_write"]:
5867
raise OSError("test: interrupted before monitor signal scope write")
@@ -70,6 +79,12 @@ def guarded_monitor_commit(**kwargs):
7079

7180
class FixtureHandler(chat_server.ChatRequestHandler):
7281
def do_POST(self):
82+
if self.path == "/__confirmation_fixture/display":
83+
patch_update = self._read_json()
84+
for name in display.keys() & patch_update.keys():
85+
display[name] = patch_update[name]
86+
self._send_json({"ok": True})
87+
return
7388
if self.path == "/__confirmation_fixture/monitor_scope":
7489
payload = self._read_json() or {}
7590
for key in ("skip_interrupt", "fail_scope_write", "unverified_scope"):
@@ -80,6 +95,8 @@ def do_POST(self):
8095
if self.path != "/__confirmation_fixture/advance":
8196
try:
8297
return super().do_POST()
98+
except (BrokenPipeError, ConnectionResetError):
99+
return
83100
except InterruptedConfirmation:
84101
self.close_connection = True
85102
return
@@ -89,6 +106,11 @@ def do_POST(self):
89106

90107
def do_GET(self):
91108
if self.path != "/__confirmation_fixture":
109+
route = self.path.split("?", 1)[0]
110+
if ((display["hold_list"] and route == "/api/actions")
111+
or (display["hold_detail"] and route.startswith("/api/actions/"))):
112+
self._send_json({"error": "test: list unavailable"}, status=503)
113+
return
92114
try:
93115
return super().do_GET()
94116
except (BrokenPipeError, ConnectionResetError):
@@ -98,6 +120,25 @@ def do_GET(self):
98120
"ids": sorted(todo["todo_id"] for todo in snapshot["todos"]),
99121
"lost": lost})
100122

123+
def _send_json(self, payload, *, status=200):
124+
gateway = display["gateway_reply"]
125+
if gateway and self.path == f"/api/actions/{gateway}/apply":
126+
display["gateway_reply"] = None
127+
body = b"<html><title>Bad Gateway</title></html>"
128+
self.send_response(502)
129+
self.send_header("Content-Type", "text/html")
130+
self.send_header("Content-Length", str(len(body)))
131+
self.end_headers()
132+
self.wfile.write(body)
133+
return
134+
operation = display["drop_reply"]
135+
if operation and self.path == f"/api/actions/{operation}/apply":
136+
display["drop_reply"] = None
137+
self.close_connection = True
138+
self.connection.shutdown(socket.SHUT_WR)
139+
return
140+
return super()._send_json(payload, status=status)
141+
101142
serve = chat_server.ChatHTTPServer.serve_forever
102143

103144
def ready(server):
@@ -107,6 +148,7 @@ def ready(server):
107148
patch.setattr(chat_server, "ChatRequestHandler", FixtureHandler)
108149
patch.setattr(chat_server.ChatHTTPServer, "serve_forever", ready)
109150
patch.setattr(ChatActionStore, "save_checkpoint", interrupt)
151+
patch.setattr(provider_projection, "atomic_write_state_text", render)
110152
patch.setattr(steward_monitor_scope, "_write_steward_monitor_scope_file", guarded_scope_write)
111153
patch.setattr(todo_creation, "check_canonical_todo_commit_current", guarded_todo_commit)
112154
patch.setattr(monitor_actions, "check_canonical_todo_commit_current", guarded_monitor_commit)

‎apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,13 +248,15 @@ export const ChannelTimeline = memo(function ChannelTimeline({
248248
const appliedTeamPlan = item.proposal.actionKind === "team.plan" && item.proposal.status === "applied";
249249
const taskReceipt = item.proposal.reviewPlan?.taskExecution;
250250
const pendingOperation = item.proposal.reviewPlan?.operationFrame?.kind === "pending";
251+
const pendingDisplay = item.proposal.reviewPlan?.reason === "canonical_create_projection_pending";
251252
return (
252253
<Fragment key={item.id}><button className={`personal-proposal-row is-${item.proposal.status}`} data-action-kind={item.proposal.actionKind} onClick={() => onSelect({ item: item.proposal, kind: "proposal" })} type="button">
253254
<span><Sparkles size={17} /></span>
254-
<span><small>{pendingOperation || item.proposal.reviewPlan?.reason === "todo_creation_retry" ? t(`proposal.kind.${item.proposal.actionKind}`)
255+
<span><small>{pendingDisplay ? t("goalWork.displayPending")
256+
: pendingOperation || item.proposal.reviewPlan?.reason === "todo_creation_retry" ? t(`proposal.kind.${item.proposal.actionKind}`)
255257
: taskReceipt ? t("drawer.taskLaunchReceipt")
256258
: appliedTeamPlan ? (locale === "zh-CN" ? "团队分配 · 已记录" : "Team assignment · Recorded")
257-
: `${t(`proposal.kind.${item.proposal.actionKind}`)} · ${t(`proposal.status.${item.proposal.status}`)}`}</small><strong>{item.proposal.title}</strong>{item.proposal.impact ? <p>{item.proposal.impact}</p> : null}</span>
259+
: `${t(`proposal.kind.${item.proposal.actionKind}`)} · ${t(`proposal.status.${item.proposal.status}`)}`}</small><strong>{item.proposal.title}</strong>{item.proposal.impact && !pendingDisplay ? <p>{item.proposal.impact}</p> : null}</span>
258260
<b>{taskReceipt ? t("feedback.taskStartRequested")
259261
: item.proposal.status === "gated" && item.proposal.actionKind !== "operation.execute" ? t("timeline.review")
260262
: item.proposal.primaryLabel ?? t("timeline.reviewAndConfirm")}</b>

‎apps/presentation/dashboard/src/features/personal-workspace/goal-workspace-work.css‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@
4242
.goal-inline-create textarea { width: 100%; min-height: 84px; resize: vertical; border: 1px solid var(--pw-line-strong); border-radius: 6px; color: var(--pw-text); background: var(--pw-bg); padding: 10px; font: inherit; }
4343
.goal-inline-create [role="alert"] { color: var(--pw-red); }
4444
.goal-inline-create form > button { justify-self: start; }
45+
.goal-task-display-recovery { margin-top: 12px; border-block: 1px solid var(--pw-line); padding-block: 8px; }
46+
.goal-task-display-recovery h3 { margin: 0; font-size: var(--text-caption); font-weight: 600; color: var(--pw-muted); }
47+
.goal-task-display-recovery ul { margin: 4px 0 0; padding: 0; list-style: none; }
48+
.goal-task-display-recovery li > button { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 12px; padding: 4px 0; min-height: 44px; border: 0; background: transparent; color: var(--pw-text); font: inherit; text-align: start; cursor: pointer; }
49+
.goal-task-display-recovery li > button span { overflow-wrap: anywhere; }
50+
.goal-task-display-recovery li > button svg { flex: none; }
4551
.goal-all-work { min-width: 0; display: grid; gap: 12px; padding-top: 8px; }
4652
.goal-work-search { display: flex; align-items: center; gap: 8px; border-bottom: 1px solid var(--pw-line); color: var(--pw-muted); }
4753
.goal-work-search input { width: 100%; min-width: 0; border: 0; padding: 10px 0; background: transparent; color: var(--pw-text); font: inherit; font-size: var(--text-body); }

0 commit comments

Comments
 (0)