Skip to content

Commit 8181a42

Browse files
kojiwakayamaclaude
andauthored
fix(agent): delegated schedule undo restores the previous status (#5686)
* fix(agent): delegated schedule undo restores the previous status user_schedule_set_status read nothing before its PATCH, so its undo named the opposite of the new status. Pausing a schedule that was already paused offered to activate it, a state it was never in. The tool now reads the schedule's status through the mapped schedules.list read before the change and returns it as previous_status; undo names that status. When the schedule already has the requested status, no write is sent and the result says no change, with nothing to undo. When the status cannot be read (no schedules.list in the grant, a failed read, the schedule not on the pages read, or a status other than active or paused), the change still happens, without previous_status and without an undo. Refs veryfront/veryfront-issue-inbox#5002 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(agent): send the schedule write even when the read shows no change A change made between the read and the skipped PATCH could leave the schedule in another status while the tool reported it as set. The tool now always sends the PATCH and reports "no change" from the read, with no undo. Refs veryfront/veryfront-issue-inbox#5002 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 25681db commit 8181a42

3 files changed

Lines changed: 218 additions & 14 deletions

File tree

‎docs/architecture/native-request-processing.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ The control plane refuses to exchange an expired grant, so the client renews bef
4242

4343
A run that carries a grant gets seven read tools built on the client: `user_projects_search`, `user_project_get`, `user_runs_list`, `user_conversations_list`, `user_inbox_read`, `user_billing_read` and `user_account_members_list`. Each tool builds a fixed API path from validated input and returns the JSON body. A run without a grant has none of these tools.
4444

45-
The run also gets a tool for each phase 2 capability that the grant names in its `authorization_details`: `user_schedules_list` (`schedules.list`), `user_project_create` (`projects.create`), `user_schedule_set_status` (`schedules.activate` or `schedules.pause`, offering only the statuses the grant carries) and `user_input_request_answer` (`input_requests.answer`). The client decodes the capabilities without verifying the signature, because they only decide which tools exist; the API checks the capability of every call. Each write sends exactly the body that the API admits for its capability, through a client helper that serializes the JSON once before the grant enters the request, so a 401 retry replays the same method and bytes. Its result states what changed and how the person can undo it. An answer carries one `Idempotency-Key`, which the retry keeps. The tool set is built once per run: a renewed grant that drops a capability stops its tool before any call, and a capability that only a renewed grant names waits for the next run. A refusal tells the model that nothing changed and why, without echoing the API body.
45+
The run also gets a tool for each phase 2 capability that the grant names in its `authorization_details`: `user_schedules_list` (`schedules.list`), `user_project_create` (`projects.create`), `user_schedule_set_status` (`schedules.activate` or `schedules.pause`, offering only the statuses the grant carries) and `user_input_request_answer` (`input_requests.answer`). The client decodes the capabilities without verifying the signature, because they only decide which tools exist; the API checks the capability of every call. Each write sends exactly the body that the API admits for its capability, through a client helper that serializes the JSON once before the grant enters the request, so a 401 retry replays the same method and bytes. Its result states what changed and how the person can undo it. `user_schedule_set_status` first reads the schedule's status through the `schedules.list` read (the API maps no single-schedule read for a grant) and returns it as `previous_status`, so undo restores that status rather than the opposite one. When the schedule already had the requested status, it still sends the write (so a change made after the read cannot leave another status behind) and reports no change, with nothing to undo. When the previous status cannot be read, the change still happens, without `previous_status` and without an undo. An answer carries one `Idempotency-Key`, which the retry keeps. The tool set is built once per run: a renewed grant that drops a capability stops its tool before any call, and a capability that only a renewed grant names waits for the next run. A refusal tells the model that nothing changed and why, without echoing the API body.
4646

4747
The same run resolves the project that a `studio_open_project` or `studio_navigate` call names, as the person, before it forwards the call. Studio receives the project's slug, or its id when it has no slug. A confirmed switch to another project ends the turn and does not re-scope the run. A run without a grant forwards the reference unchanged and continues in the new project. Only a run with a grant sends `x-veryfront-project-references: resolved` on its Studio MCP requests, so Studio skips its own lookup with the run token; the grant itself never goes to Studio.
4848

‎src/agent/hosted/delegated-user-tools.test.ts‎

Lines changed: 142 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -660,8 +660,9 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
660660
values: { approve: true, note: "ok" },
661661
});
662662

663+
const writes = calls.filter((call) => call.method !== "GET");
663664
assertEquals(
664-
calls.map((
665+
writes.map((
665666
call,
666667
) => [call.method, call.url.pathname + call.url.search, JSON.parse(call.body!)]),
667668
[
@@ -678,11 +679,11 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
678679
}],
679680
],
680681
);
681-
for (const call of calls) {
682+
for (const call of writes) {
682683
assertEquals(call.headers.get("content-type"), "application/json");
683684
assertEquals(call.headers.get("authorization")?.startsWith("Bearer "), true);
684685
}
685-
for (const call of calls.slice(0, 2)) {
686+
for (const call of writes.slice(0, 2)) {
686687
const body = JSON.parse(call.body!) as Record<string, unknown>;
687688
assert(Object.keys(body).every((key) => PROJECT_CREATE_GUARD_KEYS.includes(key)));
688689
assert(typeof body.account_id === "string");
@@ -737,10 +738,20 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
737738
});
738739

739740
it("tells the model what changed and how the person can undo it", async () => {
741+
const listed = (call: WriteCall) =>
742+
call.method === "GET"
743+
? Response.json({
744+
data: [{ id: SCHEDULE_ID, status: "active" }],
745+
page_info: { next: null },
746+
})
747+
: undefined;
740748
const { client } = grantedApi(
741749
grantWith(PHASE_2),
742750
(call) =>
743-
Response.json(call.url.pathname === "/projects" ? { id: PROJECT_ID, slug: "bright" } : {}),
751+
listed(call) ??
752+
Response.json(
753+
call.url.pathname === "/projects" ? { id: PROJECT_ID, slug: "bright" } : {},
754+
),
744755
);
745756
const tools = createHostedDelegatedUserTools(client);
746757

@@ -761,8 +772,8 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
761772
assert(String(paused.undo).includes("back to active with user_schedule_set_status"));
762773

763774
const { client: pauseOnly } = grantedApi(
764-
grantWith(["schedules.pause"]),
765-
() => Response.json({}),
775+
grantWith(["schedules.pause", "schedules.list"]),
776+
(call) => listed(call) ?? Response.json({}),
766777
);
767778
const pausedOnly = await execute(
768779
createHostedDelegatedUserTools(pauseOnly),
@@ -783,6 +794,126 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
783794
assert(String(answered.undo).includes("cannot be undone"));
784795
});
785796

797+
describe("schedule undo", () => {
798+
const schedulesPage = (items: unknown[], next: string | null = null) =>
799+
Response.json({ data: items, page_info: { next } });
800+
const setStatus = (
801+
tools: ReturnType<typeof createHostedDelegatedUserTools>,
802+
status: "active" | "paused",
803+
) =>
804+
execute(tools, "user_schedule_set_status", {
805+
project_reference: "bright-mountain",
806+
schedule_id: SCHEDULE_ID,
807+
status,
808+
}) as Promise<Record<string, unknown>>;
809+
810+
it("reports a no-op pause as no change and offers no undo", async () => {
811+
const listed = { id: SCHEDULE_ID, name: "Nightly", status: "paused" };
812+
const { calls, client } = grantedApi(
813+
grantWith(PHASE_2),
814+
(call) => call.method === "GET" ? schedulesPage([listed]) : Response.json(listed),
815+
);
816+
const result = await setStatus(createHostedDelegatedUserTools(client), "paused");
817+
// The write is still sent, so a change made after the read cannot leave another status behind.
818+
assertEquals(calls.map((call) => [call.method, call.url.pathname]), [
819+
["GET", "/projects/bright-mountain/schedules"],
820+
["PATCH", `/projects/bright-mountain/schedules/${SCHEDULE_ID}`],
821+
]);
822+
assertEquals(result.previous_status, "paused");
823+
assert(String(result.changed).startsWith("No change"), String(result.changed));
824+
assertEquals(String(result.undo).includes("back to"), false);
825+
assertEquals(result.schedule, listed);
826+
});
827+
828+
it("restores the status the schedule had before a real change", async () => {
829+
for (const [before, after] of [["active", "paused"], ["paused", "active"]] as const) {
830+
const { calls, client } = grantedApi(
831+
grantWith(PHASE_2),
832+
(call) =>
833+
call.method === "GET"
834+
? schedulesPage([{ id: SCHEDULE_ID, status: before }])
835+
: Response.json({ id: SCHEDULE_ID, status: after }),
836+
);
837+
const result = await setStatus(createHostedDelegatedUserTools(client), after);
838+
assertEquals(calls.map((call) => call.method), ["GET", "PATCH"]);
839+
assertEquals(result.previous_status, before);
840+
assert(String(result.changed).includes(`was ${before} and is now ${after}`));
841+
assert(String(result.undo).includes(`back to ${before} with user_schedule_set_status`));
842+
assertEquals(result.schedule, { id: SCHEDULE_ID, status: after });
843+
}
844+
});
845+
846+
it("follows the schedules pages to find the schedule", async () => {
847+
const cursor = "30000000-3000-4000-8000-300000000009";
848+
const { calls, client } = grantedApi(
849+
grantWith(PHASE_2),
850+
(call) => {
851+
if (call.method !== "GET") return Response.json({});
852+
return call.url.searchParams.get("cursor") === cursor
853+
? schedulesPage([{ id: SCHEDULE_ID, status: "paused" }])
854+
: schedulesPage([{ id: "other", status: "active" }], cursor);
855+
},
856+
);
857+
const result = await setStatus(createHostedDelegatedUserTools(client), "paused");
858+
assertEquals(calls.map((call) => call.url.pathname + call.url.search), [
859+
"/projects/bright-mountain/schedules?limit=100",
860+
`/projects/bright-mountain/schedules?limit=100&cursor=${cursor}`,
861+
`/projects/bright-mountain/schedules/${SCHEDULE_ID}`,
862+
]);
863+
assertEquals(result.previous_status, "paused");
864+
});
865+
866+
it("offers no undo when the previous status cannot be read", async () => {
867+
const ok = () => Response.json({});
868+
const onRead = (read: () => Response) => (call: WriteCall) =>
869+
call.method === "GET" ? read() : ok();
870+
const cases: Array<[string[], (call: WriteCall) => Response, string[]]> = [
871+
// No schedules read in the grant: nothing is read, and the change still happens.
872+
[["schedules.pause"], ok, ["PATCH"]],
873+
[PHASE_2, onRead(() => new Response("secret-detail-from-api", { status: 500 })), [
874+
"GET",
875+
"PATCH",
876+
]],
877+
[PHASE_2, onRead(() => schedulesPage([{ id: "other", status: "active" }])), [
878+
"GET",
879+
"PATCH",
880+
]],
881+
[PHASE_2, onRead(() => schedulesPage([{ id: SCHEDULE_ID, status: "deleting" }])), [
882+
"GET",
883+
"PATCH",
884+
]],
885+
[PHASE_2, onRead(() => new Response("not json")), ["GET", "PATCH"]],
886+
];
887+
for (const [actions, respond, methods] of cases) {
888+
const { calls, client } = grantedApi(grantWith(actions), respond);
889+
const result = await setStatus(createHostedDelegatedUserTools(client), "paused");
890+
assertEquals(calls.map((call) => call.method), methods);
891+
assertEquals("previous_status" in result, false);
892+
assert(String(result.changed).includes("is now paused"));
893+
assert(String(result.undo).includes("offers no undo"), String(result.undo));
894+
assertEquals(JSON.stringify(result).includes("secret-detail-from-api"), false);
895+
}
896+
});
897+
898+
it("keeps the cancellation reason when the read before the change is cancelled", async () => {
899+
const abort = new AbortController();
900+
const reason = new DOMException("stopped by the person", "AbortError");
901+
const { calls, client } = grantedApi(grantWith(PHASE_2), () => {
902+
abort.abort(reason);
903+
return Promise.reject(reason);
904+
});
905+
const error = await assertRejects(() =>
906+
execute(createHostedDelegatedUserTools(client), "user_schedule_set_status", {
907+
project_reference: "p",
908+
schedule_id: SCHEDULE_ID,
909+
status: "paused",
910+
}, { abortSignal: abort.signal })
911+
);
912+
assertEquals(error, reason);
913+
assertEquals(calls.map((call) => call.method), ["GET"]);
914+
});
915+
});
916+
786917
it("never puts the grant or the run token in tool output or model input", async () => {
787918
const grant = grantWith(PHASE_2);
788919
const console = captureConsole();
@@ -953,7 +1084,11 @@ describe("agent/hosted/delegated-user-tools capability tools", () => {
9531084
[new Response("secret-detail-from-api", { status: 500 }), "may or may not have been applied"],
9541085
];
9551086
for (const [response, expected] of cases) {
956-
const { client } = grantedApi(grantWith(PHASE_2), () => response);
1087+
const { client } = grantedApi(
1088+
grantWith(PHASE_2),
1089+
(call) =>
1090+
call.method === "GET" ? Response.json({ data: [], page_info: { next: null } }) : response,
1091+
);
9571092
const tools = createHostedDelegatedUserTools(client);
9581093
const error = await assertRejects(() =>
9591094
execute(tools, "user_schedule_set_status", {

‎src/agent/hosted/delegated-user-tools.ts‎

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,55 @@ const SCHEDULE_STATUS_CAPABILITY: Readonly<Record<ScheduleStatus, string>> = {
421421
paused: "schedules.pause",
422422
};
423423

424+
/** The schedules read pages through at most this many schedules to find one schedule's status. */
425+
const SCHEDULE_LOOKUP_PAGE_SIZE = 100;
426+
const SCHEDULE_LOOKUP_MAX_PAGES = 10;
427+
428+
/**
429+
* A schedule's status before a change, read through the mapped
430+
* `schedules.list` read (the API maps no single-schedule read for a
431+
* delegated grant). Undefined when the grant does not carry that read, the read
432+
* fails, the schedule is not on the pages read, or its status is neither active
433+
* nor paused: the caller then offers no undo rather than guessing.
434+
*/
435+
async function readScheduleStatus(
436+
api: HostedDelegatedUserApi,
437+
project: string,
438+
scheduleId: string,
439+
context: ToolExecutionContext | undefined,
440+
): Promise<ScheduleStatus | undefined> {
441+
if (!api.capabilities().includes("schedules.list")) return undefined;
442+
const abortSignal = context?.abortSignal;
443+
let cursor: string | undefined;
444+
for (let page = 0; page < SCHEDULE_LOOKUP_MAX_PAGES; page++) {
445+
let result: DelegatedJson;
446+
try {
447+
result = await getJson(
448+
api,
449+
buildPath(`/projects/${project}/schedules`, {
450+
limit: SCHEDULE_LOOKUP_PAGE_SIZE,
451+
cursor,
452+
}),
453+
abortSignal,
454+
);
455+
} catch (error) {
456+
if (abortSignal?.aborted) throw error;
457+
return undefined;
458+
}
459+
if (result.status < 200 || result.status > 299) return undefined;
460+
const data = ownValue(result.body, "data");
461+
if (!Array.isArray(data)) return undefined;
462+
for (const item of data) {
463+
if (ownValue(item, "id") !== scheduleId) continue;
464+
return SCHEDULE_STATUSES.find((known) => known === ownValue(item, "status"));
465+
}
466+
const next = ownValue(ownValue(result.body, "page_info"), "next");
467+
if (typeof next !== "string" || next.length === 0 || next === cursor) return undefined;
468+
cursor = next;
469+
}
470+
return undefined;
471+
}
472+
424473
const getSchedulesListSchema = defineSchema((v) =>
425474
v.object({
426475
project_reference: v.string().min(1).max(MAX_REFERENCE_CHARS)
@@ -659,21 +708,41 @@ function createCapabilityTools(api: HostedDelegatedUserApi): HostToolSet {
659708
requireStillGranted(SCHEDULE_STATUS_CAPABILITY[input.status]);
660709
const project = requirePathSegment(input.project_reference, "project_reference");
661710
const scheduleId = requirePathSegment(input.schedule_id, "schedule_id");
711+
const target = `schedule ${input.schedule_id} in project ${input.project_reference}`;
712+
// Read before the change, so undo restores what was there rather than the opposite.
713+
const previous = await readScheduleStatus(api, project, scheduleId, context);
662714
// Exactly { status }: the schedules.activate and schedules.pause guards admit nothing else.
715+
// Sent even when the read already shows the requested status: a change made after the read
716+
// must not leave the schedule in another status while the tool reports it as set.
663717
const schedule = await writeJson(
664718
api,
665719
`/projects/${project}/schedules/${scheduleId}`,
666720
"PATCH",
667721
{ status: input.status },
668722
context,
669723
);
670-
const opposite: ScheduleStatus = input.status === "active" ? "paused" : "active";
724+
if (previous === input.status) {
725+
return {
726+
changed: `No change: the ${target} was already ${previous}.`,
727+
undo: "Nothing changed, so there is nothing to undo.",
728+
previous_status: previous,
729+
schedule,
730+
};
731+
}
732+
if (previous === undefined) {
733+
return {
734+
changed: `The ${target} is now ${input.status}.`,
735+
undo:
736+
"Its previous status could not be read, so the agent offers no undo. The person can check the schedule in Studio.",
737+
schedule,
738+
};
739+
}
671740
return {
672-
changed:
673-
`The schedule ${input.schedule_id} in project ${input.project_reference} is now ${input.status}.`,
674-
undo: statuses.includes(opposite)
675-
? `To undo, set its status back to ${opposite} with user_schedule_set_status.`
676-
: `To undo, the person sets its status back to ${opposite} in Studio.`,
741+
changed: `The ${target} was ${previous} and is now ${input.status}.`,
742+
undo: statuses.includes(previous)
743+
? `To undo, set its status back to ${previous} with user_schedule_set_status.`
744+
: `To undo, the person sets its status back to ${previous} in Studio.`,
745+
previous_status: previous,
677746
schedule,
678747
};
679748
},

0 commit comments

Comments
 (0)