Repository navigation
fix(chat): safely steer an existing Gateway-queued input - #160275
roboclaw-bot wants to merge 3 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Before / afterActual Control UI, identical synthetic conversation and queued input, 1280×900 desktop viewport. The before capture uses the shipped bundle; the after capture uses the fix. This is a mocked-Gateway UI fixture, not a live model run. BeforeThe Gateway-queued row offers delete but no Steer action. AfterThe same original queued input offers Steer beside delete. |
|
Codex review: blocked before merge. Reviewed September 30, 2026, 11:47 PM ET / October 1, 2026, 03:47 UTC (Revision 5). ClawSweeper reviewWhat this changesAdds a Gateway control that steers an original queued chat input into an active turn while preserving its attachments, identity, authorization, and rejection handling. Merge readiness⛔ Blocked before merge - 1 item remains This PR remains useful: current main lacks the queued-input control, and the reviewed changes address the earlier custody and authorization concerns. No actionable introduced defect remains; the previous stored-format warning is unsupported by the actual diff. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway admits chat inputs and queues them while an agent is busy. This control promotes an existing queued input through the agent’s established injection and transcript-writing paths, then reports its custody outcome. flowchart TD
A[Authorized chat client] --> B[Gateway session authorization]
B --> C[Original queued input]
C --> D[Reserve input in place]
D --> E[Active agent injection]
E --> F[Guarded transcript and transport]
E --> G[Rejected input stays queued]
F --> H[Custody receipt]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +504, Tests +1452, Docs +3, Other +27. Total +1986 across 41 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep queued promotion with the existing queue and injection owners, preserving exact source identity and live authority through definitive settlement. Do we have a high-confidence way to reproduce the issue? Not applicable as a new backend control: current-main source confirms that fresh steering exists but promotion of an already queued source is unavailable. Is this the best way to solve the issue? Yes. Extending the existing queue owner and guarded injection path avoids resending input or creating competing custody state. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 55fe1b488910. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
f3947e2 to
efef44c
Compare
|
Here's the data-model compatibility proof from the open ClawSweeper item. This PR doesn't change anything that's stored. Diff check (
Run check
Both builds write the same schema and the same rows, so either one reads a database written by the other. Upgrading or rolling back needs no migration. Limits: the Codex app-server is the existing test harness, not a live provider. The steered message is text only, with no attachments. How to rerun it
// Throwaway proof for openclaw/openclaw#160275: run unchanged on the PR base and head,
// then diff the normalized dumps. Not part of the PR.
import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from "node:fs";
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import type { setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
import { loadUserTurnTranscriptRecorderFactoryForTest } from "openclaw/plugin-sdk/plugin-test-runtime";
import { readSessionTranscriptEvents } from "openclaw/plugin-sdk/session-transcript-runtime";
import { describe, expect, it, vi } from "vitest";
import { isJsonObject } from "./protocol.js";
import {
createStartedThreadHarness,
createTestParams,
runCodexAppServerAttempt,
setupRunAttemptTestHooks,
} from "./run-attempt-test-harness.js";
import { attachSqliteSessionTarget } from "./sqlite-session.test-helpers.js";
const registrations = vi.hoisted(() => vi.fn());
vi.mock("openclaw/plugin-sdk/agent-harness-runtime", async (importOriginal) => {
const actual = await importOriginal<typeof import("openclaw/plugin-sdk/agent-harness-runtime")>();
return {
...actual,
setActiveEmbeddedRun: (...args: Parameters<typeof actual.setActiveEmbeddedRun>) => {
registrations(...args);
return actual.setActiveEmbeddedRun(...args);
},
};
});
setupRunAttemptTestHooks();
function normalizeText(text: string, tmp: string): string {
return text
.replaceAll(tmp, "<tmp>")
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<uuid>")
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z/g, "<iso>")
.replace(/(?<![\d.])1[78]\d{11}(?![\d.])/g, "<ts>");
}
function normalize(value: unknown, tmp: string): unknown {
return JSON.parse(
JSON.stringify(value, (_key, v) => {
if (typeof v === "bigint") {
v = Number(v);
}
if (typeof v === "number" && v > 1e12 && v < 2e12) {
return "<ts>";
}
if (typeof v === "string") {
// Stored JSON columns are normalized as parsed values, so key order and volatile ids compare cleanly.
if (/^[[{]/.test(v)) {
try {
return { json: normalize(JSON.parse(v), tmp) };
} catch {}
}
return normalizeText(v, tmp);
}
if (v instanceof Uint8Array) {
return `<blob ${v.byteLength} bytes>`;
}
return v;
}),
);
}
function findSqliteFiles(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const file = path.join(dir, name);
if (statSync(file).isDirectory()) {
return findSqliteFiles(file);
}
return /\.(sqlite|db)$/.test(name) ? [file] : [];
});
}
describe("data-model compatibility proof", () => {
it("records the stored state of one queued input steered into a Codex turn", async () => {
const out = expectDefined(process.env.PROOF_OUT, "PROOF_OUT");
registrations.mockReset();
const params = createTestParams();
const tmp = path.dirname(params.workspaceDir);
await attachSqliteSessionTarget(
params,
path.join(params.workspaceDir, "commit.sqlite"),
"commit-authority",
);
const target = {
...expectDefined(params.sessionTarget, "session target"),
agentId: "main",
sessionId: params.sessionId,
sessionKey: expectDefined(params.sessionKey, "session key"),
sessionEntry: undefined,
};
const createRecorder = await loadUserTurnTranscriptRecorderFactoryForTest();
const registered = createDeferred<Parameters<typeof setActiveEmbeddedRun>[1]>();
registrations.mockImplementation(
(id: string, handle: Parameters<typeof setActiveEmbeddedRun>[1]) => {
if (id === params.sessionId) {
registered.resolve(handle);
}
},
);
const text = "Use metric units.";
const recorder = createRecorder({
input: { text, timestamp: 1, idempotencyKey: "queued-source:user" },
target: async () => target,
});
expect(
await recorder.stageApproved?.({ runId: "queued-source", assertCurrent: () => {} }),
).toBe(true);
const harness = createStartedThreadHarness();
const run = runCodexAppServerAttempt(params);
let completed = false;
try {
const handle = await registered.promise;
const delivery = expectDefined(handle.messageInjectionV2, "V2 injection").queueMessage(
text,
{ debounceMs: 0, isInboundUserMessage: true, userTurnTranscriptRecorder: recorder },
() => {},
"source-bound",
);
await harness.waitForMethod("turn/steer");
const request = expectDefined(
harness.requests.find((entry) => entry.method === "turn/steer"),
"steer request",
);
const wire = expectDefined(
isJsonObject(request.params) ? request.params : undefined,
"wire parameters",
);
await harness.notify({
method: "item/completed",
params: {
threadId: "thread-1",
turnId: "turn-1",
item: { id: "steered-source", type: "userMessage", clientId: wire.clientUserMessageId },
},
});
await delivery;
expect(recorder.hasPersisted()).toBe(true);
const events = await readSessionTranscriptEvents({
agentId: "main",
sessionId: params.sessionId,
sessionKey: target.sessionKey,
storePath: target.storePath,
});
completed = true;
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
await run;
mkdirSync(path.join(out, "db"), { recursive: true });
writeFileSync(
path.join(out, "steer-request.json"),
`${JSON.stringify(normalize(request.params, tmp), null, 2)}\n`,
);
writeFileSync(
path.join(out, "transcript-events.json"),
`${JSON.stringify(normalize(events, tmp), null, 2)}\n`,
);
// Copy the stored files; they are dumped outside the test so this test never opens them itself.
for (const file of findSqliteFiles(tmp)) {
for (const suffix of ["", "-wal", "-shm"]) {
if (existsSync(file + suffix)) {
copyFileSync(file + suffix, path.join(out, "db", path.basename(file) + suffix));
}
}
}
} finally {
if (!completed) {
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
await run;
}
}
});
});
// Usage: node dump-db.mjs <copied.sqlite> > dump.json
// Dumps schema, user_version and every row with volatile ids/timestamps normalized.
import { DatabaseSync } from "node:sqlite";
function normalizeText(text) {
return text
.replace(/\/[^"\s]*openclaw-codex-run-[^/"\s]*/g, "<tmp>")
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<uuid>")
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z/g, "<iso>")
.replace(/(?<![\d.])1[78]\d{11}(?![\d.])/g, "<ts>");
}
function normalize(value) {
return JSON.parse(
JSON.stringify(value, (_key, v) => {
if (typeof v === "bigint") v = Number(v);
if (typeof v === "number" && v > 1e12 && v < 2e12) return "<ts>";
if (typeof v === "string") {
if (/^[[{]/.test(v)) {
try {
return { json: normalize(JSON.parse(v)) };
} catch {}
}
return normalizeText(v);
}
if (v instanceof Uint8Array) return `<blob ${v.byteLength} bytes>`;
return v;
}),
);
}
const db = new DatabaseSync(process.argv[2]);
const schema = db
.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name")
.all();
const tables = {};
for (const { type, name } of schema) {
if (type !== "table" || name.startsWith("sqlite_")) continue;
const rows = db.prepare(`SELECT * FROM "${name}"`).all();
if (rows.length > 0) tables[name] = rows;
}
const userVersion = db.prepare("PRAGMA user_version").get().user_version;
db.close();
console.log(JSON.stringify(normalize({ userVersion, schema, tables }), null, 2));This also unblocks iOS. We closed #187078 so queued messages stay in the Gateway queue, and the iOS Steer action will use |
Reuse current session access, prepared row facts, and the original controller source. Preserve FIFO fallback and settle possible native commitment without replay. Co-authored-by: vyctorbrzezowski <[email protected]>
Worked on by: - @vyctorbrzezowski Co-authored-by: vyctorbrzezowski <[email protected]> OpenClaw-Publication: 5f4eda6b-790e-4ee8-be00-d1b7fca07518
Worked on by: - @vyctorbrzezowski Co-authored-by: vyctorbrzezowski <[email protected]> OpenClaw-Publication: afc43178-e2a4-4b2c-9c5e-f01e61b947f4
efef44c to
3b8a4bb
Compare
Current-source queued-input Steer proofSynthetic data. Real source Control UI in Chromium with a mock Gateway; base Before: the Gateway-held queued chip has no Steer action. After: the same custody state exposes Steer. The browser scenario also exercised identity-only control, busy state, custody retirement and retained draft text. |




What Problem This Solves
Fixes: a message already held in the Gateway queue has no safe way to join compatible active work without being sent again.
User Impact
Authorized clients can attempt to steer the original queued input, including approved content and attachments. A definite refusal preserves its queue position; possible native commitment must not replay. No configuration, storage migration, or protocol-version bump is introduced.
Backend slice. The visible Control UI affordance is stacked follow-up #160593. This task does not authorize merging or deployment.
Why This Change Was Made
The current session controller remains the only custody owner.
chat.steerselects the original source by session/run identity and prepared physical-store scope, uses the router's current session-access authority, and shares ordinary steering policy and native settlement. It neither reconstructs the message nor creates another queued input. Incompatible model or authority leaves the input queued.Evidence
chat.send, the original prepared queued source, registeredchat.steer, real session projection/authorization and SQLite; only the model backend is stubbed. It verifies one injection of original content, its original recorder, a completed original protocol receipt, no abandonment, source retirement, and no later execution.63c25f72daff6906c011027195a3187c8d8b7f06, P0–P2, two native passes, no actionable findings. One subsequent test-only lint correction removedawaitfrom synchronous projection disposal; affected lint and the standalone regression passed afterward.Limits: model delivery is simulated in boundary tests. No live-provider or installed-upgrade rehearsal was run. Native generated contracts were checked, not native application builds. Hosted checks must be read against the published head; local results are not current-head CI. The refreshed code and evidence are published; both PRs remain drafts under this build-PRs-only task.
Failure investigation and generated diff
The registered entry point caught a real wrong-owner defect despite an earlier static review: requiring the legacy mutation target rejected a valid current-router request as “conversation changed.” The handler now consumes current session-access authority and the existing prepared-read owner. The unchanged acceptance and settlement assertions pass after that repair.
Separate fixture defects were corrected without weakening product checks: reused ingress IDs collided with process-wide dedupe; the direct context lacked a ready row projection; and a hardcoded incumbent model differed from the actual configured incoming model, which production correctly refused. The fixture now uses a unique ID, real projection, and configured-model resolver. Earlier setup timeouts are not passing or product-failure evidence.
Most line churn is canonical generated-predicate renumbering. The independent review included those changes. The initial oversized review request failed before assessment; native partitioning retained the complete change and owner contracts within the transport limit. CI cost is unavailable until a run exists.
Reported by @vyctorbrzezowski.
Worked on by
Work sessions
View the OpenClaw team session