Skip to content

Commit ce7e753

Browse files
committed
fix: preserve document task progress for invalid fields
1 parent 3429349 commit ce7e753

3 files changed

Lines changed: 214 additions & 16 deletions

File tree

‎apps/mobile/src/agent-ui.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,21 @@ function errorText(e: unknown) {
7272
function activeTask(task: AgentTask) {
7373
return !["succeeded", "failed", "cancelled"].includes(task.status);
7474
}
75+
function recoverableDocumentValues(task: AgentTask) {
76+
if (task.kind !== "document" || task.status !== "waiting_input") return {};
77+
const values = task.input.fields;
78+
if (!values || typeof values !== "object" || Array.isArray(values)) return {};
79+
const supported = Array.isArray(task.state.missingFields) ? task.state.missingFields : [];
80+
const result: Record<string, string | boolean> = {};
81+
for (const field of supported) {
82+
if (!field || typeof field !== "object" || !("name" in field) || !("type" in field)) continue;
83+
const name = String(field.name);
84+
const value = (values as Record<string, unknown>)[name];
85+
if (field.type === "checkbox" ? typeof value === "boolean" : typeof value === "string")
86+
result[name] = value as string | boolean;
87+
}
88+
return result;
89+
}
7590
export function AgentStatus() {
7691
const { data, error, refresh } = useAgentWorkspace();
7792
if (data?.worker.running && !error) return null;
@@ -298,6 +313,7 @@ export function TaskDetail({ taskId }: { taskId: string }) {
298313
.then((result) => {
299314
if (active) {
300315
setDetail(result);
316+
setFields(recoverableDocumentValues(result.task));
301317
setError("");
302318
}
303319
})
@@ -372,6 +388,21 @@ export function TaskDetail({ taskId }: { taskId: string }) {
372388
: "",
373389
)
374390
.filter(Boolean);
391+
const fieldErrors = Array.isArray(task?.state.fieldErrors)
392+
? task.state.fieldErrors
393+
.filter(
394+
(issue) =>
395+
issue &&
396+
typeof issue === "object" &&
397+
"name" in issue &&
398+
"expected" in issue &&
399+
"received" in issue,
400+
)
401+
.map(
402+
(issue) =>
403+
`${String(issue.name)}: expected ${String(issue.expected)}, received ${String(issue.received)}`,
404+
)
405+
: [];
375406
return (
376407
<Sheet
377408
title={task?.title || "Task"}
@@ -452,6 +483,7 @@ export function TaskDetail({ taskId }: { taskId: string }) {
452483
{task.status === "waiting_input" && (
453484
<Card style={{ backgroundColor: colors.sky, gap: 10 }}>
454485
<Text style={s.heading}>{task.question || "A detail from you will help"}</Text>
486+
<ErrorNotice error={fieldErrors.join("\n")} />
455487
{fieldNames.map((name) =>
456488
missing.some(
457489
(f) => typeof f === "object" && f && f.name === name && f.type === "checkbox",

‎apps/server/src/engine/service.ts‎

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
import { LostLeaseError, type TaskContext, TaskWorker } from "./worker.ts";
4646

4747
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
48+
const documentFieldsSchema = z.record(z.string(), z.union([z.string(), z.boolean()]));
4849
/** A change watch's last saved page: its hash, relative-time-free fingerprint and lines. */
4950
type MonitorPage = { id: string; hash?: string; timelessHash?: string; lines: string[] };
5051
const date = () => new Date().toISOString();
@@ -348,6 +349,16 @@ export class AgentService {
348349
...taskAnswers(task.state),
349350
{ ...(task.question ? { question: task.question } : {}), answer },
350351
];
352+
const existingFields =
353+
task.kind === "document" ? documentFieldsSchema.safeParse(task.input.fields) : undefined;
354+
const nextFields = fields
355+
? { ...(existingFields?.success ? existingFields.data : {}), ...fields }
356+
: undefined;
357+
const nextState: Record<string, unknown> = { ...state, answers };
358+
if (task.kind === "document") {
359+
delete nextState.missingFields;
360+
delete nextState.fieldErrors;
361+
}
351362
const next = await this.db.compareAndSwap<AgentTask>(
352363
owner,
353364
"tasks",
@@ -356,8 +367,8 @@ export class AgentService {
356367
{
357368
status: "queued",
358369
question: null,
359-
input: { ...task.input, ...(fields ? { fields } : {}) },
360-
state: { ...state, answers },
370+
input: { ...task.input, ...(nextFields ? { fields: nextFields } : {}) },
371+
state: nextState,
361372
updatedAt: date(),
362373
},
363374
);
@@ -1001,27 +1012,48 @@ export class AgentService {
10011012
});
10021013
await ctx.event("step", "Found the document", file.name);
10031014
}
1004-
const fields = z
1005-
.record(z.string(), z.union([z.string(), z.boolean()]))
1006-
.optional()
1007-
.parse(task.input.fields);
1015+
const fields = documentFieldsSchema.optional().parse(task.input.fields);
1016+
const file = await this.files.get(owner, source.fileId);
1017+
const supportedFields = file.fields?.filter((field) => field.type !== "unsupported") ?? [];
1018+
if (!supportedFields.length)
1019+
throw new Error("This PDF has no supported fillable fields. Open it in Files to review it.");
10081020
if (!fields || !Object.keys(fields).length) {
1009-
const file = await this.files.get(owner, source.fileId);
1010-
const names = file.fields
1011-
?.filter((f) => f.type !== "unsupported")
1012-
.map((f) => f.name)
1013-
.join(", ");
1014-
if (!names)
1015-
throw new Error(
1016-
"This PDF has no supported fillable fields. Open it in Files to review it.",
1017-
);
1021+
const names = supportedFields.map((field) => field.name).join(", ");
10181022
return {
10191023
status: "waiting_input",
10201024
question: `Enter the form values you want to use. Supported fields: ${names}. The original PDF will stay intact.`,
10211025
state: {
10221026
...task.state,
10231027
source,
1024-
missingFields: file.fields?.filter((f) => f.type !== "unsupported"),
1028+
missingFields: supportedFields,
1029+
},
1030+
};
1031+
}
1032+
const supportedByName = new Map(supportedFields.map((field) => [field.name, field]));
1033+
const acceptedFields: Record<string, string | boolean> = {};
1034+
const fieldErrors: { name: string; expected: string; received: string }[] = [];
1035+
for (const [name, value] of Object.entries(fields)) {
1036+
const field = supportedByName.get(name);
1037+
const expected = field?.type === "checkbox" ? "boolean" : "string";
1038+
if (!field)
1039+
fieldErrors.push({ name, expected: "a supported PDF field", received: typeof value });
1040+
else if (typeof value !== expected)
1041+
fieldErrors.push({ name, expected, received: typeof value });
1042+
else acceptedFields[name] = value;
1043+
}
1044+
if (fieldErrors.length) {
1045+
const details = fieldErrors
1046+
.map(({ name, expected, received }) => `${name} needs ${expected}, received ${received}`)
1047+
.join("; ");
1048+
return {
1049+
status: "waiting_input",
1050+
question: `Correct the form values before filling the PDF. ${details}. The original PDF and valid values will stay intact.`,
1051+
input: { ...task.input, fields: acceptedFields },
1052+
state: {
1053+
...task.state,
1054+
source,
1055+
missingFields: supportedFields,
1056+
fieldErrors,
10251057
},
10261058
};
10271059
}

‎tests/workflows.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,140 @@ test("document job runs without a client, waits for review, and resumes from its
106106
);
107107
});
108108

109+
test("document job preserves valid fields while asking to repair an invalid checkbox", async () => {
110+
const recoveryOwner = "document-field-recovery";
111+
await server.workspace.ensureSample(recoveryOwner, server.actions);
112+
const workspace = await server.workspace.snapshot(recoveryOwner);
113+
const mail = workspace.mail.find((message) => message.attachments.length);
114+
assert.ok(mail);
115+
const task = await server.agent.createTask(recoveryOwner, {
116+
prompt: "Fill the sample form and prepare a reply",
117+
kind: "document",
118+
input: {
119+
messageId: mail.id,
120+
fields: {
121+
participant_name: "Test Student",
122+
guardian_name: "Test Guardian",
123+
permission_granted: "true",
124+
},
125+
},
126+
});
127+
128+
await server.agent.worker.tick();
129+
const waiting = await server.agent.getTask(recoveryOwner, task.id);
130+
assert.equal(waiting.status, "waiting_input", waiting.error ?? waiting.question);
131+
assert.equal(waiting.plan[0]?.status, "succeeded");
132+
assert.equal(waiting.plan[1]?.status, "pending");
133+
assert.ok(waiting.state.source);
134+
assert.deepEqual(waiting.input.fields, {
135+
participant_name: "Test Student",
136+
guardian_name: "Test Guardian",
137+
});
138+
assert.deepEqual(waiting.state.fieldErrors, [
139+
{
140+
name: "permission_granted",
141+
expected: "boolean",
142+
received: "string",
143+
},
144+
]);
145+
assert.equal(
146+
(await db.list<Artifact>(recoveryOwner, "files")).filter((file) => file.parentId).length,
147+
0,
148+
);
149+
const source = waiting.state.source as { fileId: string };
150+
151+
await server.agent.answer(recoveryOwner, task.id, "Use a checked checkbox", {
152+
permission_granted: true,
153+
});
154+
await server.agent.worker.tick();
155+
156+
const reviewed = await server.agent.detail(recoveryOwner, task.id);
157+
assert.equal(
158+
reviewed.task.status,
159+
"waiting_approval",
160+
reviewed.task.error ?? reviewed.task.question,
161+
);
162+
assert.equal((reviewed.task.state.source as { fileId: string }).fileId, source.fileId);
163+
assert.deepEqual(reviewed.task.input.fields, {
164+
participant_name: "Test Student",
165+
guardian_name: "Test Guardian",
166+
permission_granted: true,
167+
});
168+
assert.equal(reviewed.task.state.fieldErrors, undefined);
169+
assert.equal(reviewed.task.state.missingFields, undefined);
170+
assert.deepEqual(reviewed.task.state.answers, [
171+
{
172+
question: waiting.question,
173+
answer: "Use a checked checkbox",
174+
},
175+
]);
176+
assert.equal(reviewed.files.length, 1);
177+
});
178+
179+
test("document job preserves valid fields while asking to replace an unknown field", async () => {
180+
const recoveryOwner = "document-field-name-recovery";
181+
await server.workspace.ensureSample(recoveryOwner, server.actions);
182+
const workspace = await server.workspace.snapshot(recoveryOwner);
183+
const mail = workspace.mail.find((message) => message.attachments.length);
184+
assert.ok(mail);
185+
const task = await server.agent.createTask(recoveryOwner, {
186+
prompt: "Fill the sample form and prepare a reply",
187+
kind: "document",
188+
input: {
189+
messageId: mail.id,
190+
fields: {
191+
participant_name: "Test Student",
192+
guardian_name: "Test Guardian",
193+
consent: true,
194+
},
195+
},
196+
});
197+
198+
await server.agent.worker.tick();
199+
const waiting = await server.agent.getTask(recoveryOwner, task.id);
200+
assert.equal(waiting.status, "waiting_input", waiting.error ?? waiting.question);
201+
assert.equal(waiting.plan[0]?.status, "succeeded");
202+
assert.equal(waiting.plan[1]?.status, "pending");
203+
assert.ok(waiting.state.source);
204+
assert.deepEqual(waiting.input.fields, {
205+
participant_name: "Test Student",
206+
guardian_name: "Test Guardian",
207+
});
208+
assert.deepEqual(waiting.state.fieldErrors, [
209+
{
210+
name: "consent",
211+
expected: "a supported PDF field",
212+
received: "boolean",
213+
},
214+
]);
215+
assert.equal(
216+
(await db.list<Artifact>(recoveryOwner, "files")).filter((file) => file.parentId).length,
217+
0,
218+
);
219+
const source = waiting.state.source as { fileId: string };
220+
221+
await server.agent.answer(recoveryOwner, task.id, "Use the PDF's checkbox field", {
222+
permission_granted: true,
223+
});
224+
await server.agent.worker.tick();
225+
226+
const reviewed = await server.agent.detail(recoveryOwner, task.id);
227+
assert.equal(
228+
reviewed.task.status,
229+
"waiting_approval",
230+
reviewed.task.error ?? reviewed.task.question,
231+
);
232+
assert.equal((reviewed.task.state.source as { fileId: string }).fileId, source.fileId);
233+
assert.deepEqual(reviewed.task.input.fields, {
234+
participant_name: "Test Student",
235+
guardian_name: "Test Guardian",
236+
permission_granted: true,
237+
});
238+
assert.equal(reviewed.task.state.fieldErrors, undefined);
239+
assert.equal(reviewed.task.state.missingFields, undefined);
240+
assert.equal(reviewed.files.length, 1);
241+
});
242+
109243
test("document retry reuses the filled PDF after its task checkpoint is lost", async (t) => {
110244
const replayOwner = "interrupted-document";
111245
await server.workspace.ensureSample(replayOwner, server.actions);

0 commit comments

Comments
 (0)