Skip to content

Commit d166f57

Browse files
authored
fix(chat): recover unanswered questions from helpers (#5521)
* fix(chat): recover unanswered questions from helpers Watch helpers found through a running task, and helpers of helpers, and re-check questions and approvals every five seconds while a watched session is active or waiting, so a missed live update cannot leave delegated work blocked. Signed-off-by: Jalil <reachjalil@gmail.com> * test(chat): read the recovered answer through the helper's chat The proof recovered and answered the helper's question, then waited for the answer text to become visible in the parent. CI found that text only in a hidden element there: the completed task opens the helper's chat rather than showing its answer inline. Wait for the native request to settle, open the helper's chat and read the answer through its question disclosure, as the earlier delegated question journey did. Use the delegated question world as dev provides it, which already runs in the web app, instead of a separate surface wrapper. Signed-off-by: Jalil <reachjalil@gmail.com> --------- Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent b1d3ce0 commit d166f57

3 files changed

Lines changed: 144 additions & 4 deletions

File tree

‎apps/app/src/react-app/domains/session/sync/use-session-interactions.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { t } from "@/i18n";
1111
import { useQueryCacheArrayState, useQueryCacheState } from "@/react-app/infra/query-cache-state";
1212
import { getReactQueryClient } from "@/react-app/infra/query-client";
1313
import { describeRouteError } from "@/react-app/shell/route-workspaces";
14+
import { createSessionChildIdsSelector, useSessionActivityStore } from "../status/session-activity-store";
1415
import {
1516
permissionKey,
1617
questionKey,
@@ -239,10 +240,12 @@ function createInteractionHydration(client: Client, workspaceId: string, session
239240
const newChild = (): PermissionHydration => ({
240241
controller: new AbortController(), snapshot: { startedAt: 0 }, legacy, done: false,
241242
});
242-
const refresh = () => {
243+
const refreshIds = (ids: Iterable<string>) => {
243244
if (disposed) return;
244245
refreshShared();
245-
for (const [id, child] of children) {
246+
for (const id of ids) {
247+
const child = children.get(id);
248+
if (!child) continue;
246249
if (child.done) {
247250
const next = newChild();
248251
children.set(id, next);
@@ -251,6 +254,18 @@ function createInteractionHydration(client: Client, workspaceId: string, session
251254
}
252255
drain();
253256
};
257+
const refresh = () => refreshIds(children.keys());
258+
// A child may ask after the initial shared snapshot, while its live event
259+
// is missed. Reconcile only active or blocked sessions, using the same
260+
// bounded queue and snapshot fences as initial hydration and reconnect.
261+
const interval = window.setInterval(() => {
262+
const records = useSessionActivityStore.getState().recordsByWorkspaceId[workspaceId] ?? {};
263+
const ids = [...children.keys()].filter(id => {
264+
const record = records[id];
265+
return record?.runActive || record?.waitingPermissionIds.length || record?.waitingQuestionIds.length;
266+
});
267+
if (ids.length) refreshIds(ids);
268+
}, 5_000);
254269
const onVisibilityChange = () => { if (document.visibilityState === "visible") refresh(); };
255270
refreshShared();
256271
window.addEventListener("online", refresh);
@@ -283,6 +298,7 @@ function createInteractionHydration(client: Client, workspaceId: string, session
283298
},
284299
dispose() {
285300
disposed = true;
301+
window.clearInterval(interval);
286302
legacy?.controller.abort();
287303
questions?.controller.abort();
288304
for (const child of children.values()) child.controller.abort();
@@ -312,11 +328,21 @@ export function useSessionInteractions(input: UseSessionInteractionsInput) {
312328
const questionReplyBusyRef = useRef(false);
313329

314330
const requestedSessionIdsKey = (input.interactionSessionIds ?? []).join("\u0000");
331+
const selectChildIds = useMemo(createSessionChildIdsSelector, []);
332+
const childrenBySession = useSessionActivityStore(selectChildIds)[workspaceId ?? ""];
315333
const interactionSessionIds = useMemo(() => {
316334
if (!sessionId) return [];
317335
const requested = requestedSessionIdsKey ? requestedSessionIdsKey.split("\u0000") : [];
318-
return Array.from(new Set([sessionId, ...requested].map((id) => id.trim()).filter(Boolean)));
319-
}, [requestedSessionIdsKey, sessionId]);
336+
const inventory = new Set<string>();
337+
const queue = [sessionId, ...requested];
338+
for (let index = 0; index < queue.length; index += 1) {
339+
const id = queue[index]?.trim();
340+
if (!id || inventory.has(id)) continue;
341+
inventory.add(id);
342+
queue.push(...(childrenBySession?.[id] ?? []));
343+
}
344+
return [...inventory];
345+
}, [childrenBySession, requestedSessionIdsKey, sessionId]);
320346
const permissionQueryKeys = useMemo(
321347
() => workspaceId ? interactionSessionIds.map((id) => permissionKey(workspaceId, id)) : [],
322348
[interactionSessionIds, workspaceId],
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { expect } from "vitest";
2+
import { spec } from "@openwork/testkit";
3+
import { isRecord } from "../worlds/library.ts";
4+
import { childDecisionsWeb } from "../worlds/child-decisions.ts";
5+
6+
const test = spec.world(childDecisionsWeb, { timeout: 420_000,
7+
resources: { surfaces: ["appWeb"], services: ["mock"] } });
8+
9+
test("a member recovers a helper's unanswered question after losing its live notification", async ({ world, user, probe, step, evidence }) => {
10+
const pending = async () => {
11+
const response = await world.nativePendingDecisions();
12+
expect(response.status).toBe(200);
13+
const data = isRecord(response.body) && "data" in response.body ? response.body.data : response.body;
14+
if (!Array.isArray(data)) throw new Error("Native pending decisions did not return a list");
15+
return data.filter(isRecord).map(item => ({ id: item.id, sessionID: item.sessionID }));
16+
};
17+
await step("before: another task has its own unanswered question", async () => {
18+
await user.reload();
19+
await user.type("composer", world.unrelated.prompt, { verify: true });
20+
await probe.eventually(() => probe.composer(), { within: 30_000, label: "the configured engine admits the request", until: state => state.runTaskEnabled });
21+
await user.click("Run task");
22+
await user.see({ text: world.unrelated.question }, { timeoutMs: 60_000 });
23+
expect(await pending()).toEqual([expect.objectContaining({ sessionID: world.unrelated.sessionId })]);
24+
await user.screenshot();
25+
});
26+
const unrelated = await pending();
27+
await step("the member delegates work while live question notifications are lost", async () => {
28+
await user.click({ text: "Delegated question parent" });
29+
await user.see("composer", { editable: true });
30+
await world.armNotificationFault();
31+
await user.type("composer", world.root.prompt, { verify: true });
32+
await probe.eventually(() => probe.composer(), { within: 30_000, label: "the parent can admit delegated work", until: state => state.runTaskEnabled });
33+
await user.click("Run task");
34+
const dropped = await probe.eventually(() => world.notificationDrops(), {
35+
within: 60_000, label: "the real helper question notification was dropped", until: count => count >= 1,
36+
});
37+
expect(dropped).toBeGreaterThanOrEqual(1);
38+
});
39+
await step("after: the parent recovers only its helper's question", async () => {
40+
await user.see({ text: world.child.question }, { timeoutMs: 30_000 });
41+
await user.notSee({ text: world.unrelated.question });
42+
const requests = await pending();
43+
expect(requests).toHaveLength(2);
44+
expect(requests).toEqual(expect.arrayContaining(unrelated));
45+
expect((await probe.dom(`[data-session-surface-id="${world.root.sessionId}"]`)).elements).toHaveLength(1);
46+
await user.screenshot();
47+
});
48+
await step("reload keeps the question answerable and answering resumes the original work", async () => {
49+
await user.reload();
50+
await user.see({ text: world.child.question }, { timeoutMs: 60_000 });
51+
await user.click({ role: "button", label: /^Child checklist/ });
52+
await probe.eventually(pending, {
53+
within: 60_000, label: "only the helper's request is settled",
54+
until: items => items.length === 1 && items[0]?.id === unrelated[0]?.id,
55+
});
56+
expect(await pending()).toEqual(unrelated);
57+
await user.notSee({ text: world.unrelated.question });
58+
// The completed task is a doorway into the helper's chat, not an inline
59+
// copy of its answer. Read the answer through the helper's own disclosure.
60+
await user.click({ role: "button", label: "Choose delegated task format. Open sub-agent chat" });
61+
await user.see({ role: "button", label: "Task format Answered" }, { timeoutMs: 90_000 });
62+
await user.click({ role: "button", label: "Task format Answered" });
63+
await user.see({ text: /User has answered your questions:.*="Child checklist"/ });
64+
await user.notSee({ text: world.unrelated.question });
65+
await user.screenshot();
66+
});
67+
});

‎evals/worlds/child-decisions.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { addInitScript, browserScript } from "@openwork/cdp";
2+
import type { Seed } from "@openwork/env";
3+
import { delegatedQuestionHandoff } from "./chat.ts";
4+
5+
export async function childDecisionsWeb(seed: Seed) {
6+
const world = await delegatedQuestionHandoff(seed);
7+
// Inject a transport fault before the next page load. The engine still owns
8+
// real pending forms; only their live notification is lost. Snapshot reads,
9+
// tool progress, session ownership and answers pass through unchanged.
10+
await addInitScript(world.app.client, () => {
11+
Reflect.set(window, "__childDecisionNotificationsDropped", 0);
12+
Reflect.set(window, "__dropChildDecisionNotifications", false);
13+
const original = window.fetch.bind(window);
14+
window.fetch = async (...args) => {
15+
const response = await original(...args);
16+
if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream")) return response;
17+
const decoder = new TextDecoder();
18+
const encoder = new TextEncoder();
19+
let buffer = "";
20+
const filtered = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
21+
transform(chunk, controller) {
22+
buffer += decoder.decode(chunk, { stream: true });
23+
const frames = buffer.split(/\r?\n\r?\n/);
24+
buffer = frames.pop() ?? "";
25+
for (const frame of frames) {
26+
if (Reflect.get(window, "__dropChildDecisionNotifications") && /"type"\s*:\s*"(?:form\.created|question\.asked)"/.test(frame)) {
27+
Reflect.set(window, "__childDecisionNotificationsDropped", Number(Reflect.get(window, "__childDecisionNotificationsDropped")) + 1);
28+
} else controller.enqueue(encoder.encode(frame + "\n\n"));
29+
}
30+
},
31+
flush(controller) { if (buffer) controller.enqueue(encoder.encode(buffer)); },
32+
}));
33+
return new Response(filtered, { status: response.status, headers: response.headers });
34+
};
35+
});
36+
return { ...world,
37+
armNotificationFault: () => seed.evalIn(world.app, () => { Reflect.set(window, "__dropChildDecisionNotifications", true); }),
38+
notificationDrops: () => seed.evalIn(world.app, () => Number(Reflect.get(window, "__childDecisionNotificationsDropped"))),
39+
nativePendingDecisions: () => seed.evalIn(world.app, browserScript(async (workspaceId, engine) => {
40+
const base = "http://127.0.0.1:" + localStorage.getItem("openwork.server.port")
41+
+ "/workspace/" + encodeURIComponent(workspaceId) + (engine === "v2" ? "/opencode2/api/form/request" : "/opencode/question");
42+
const response = await fetch(base, { headers: { Authorization: "Bearer " + localStorage.getItem("openwork.server.token") } });
43+
const body: unknown = await response.json();
44+
return { status: response.status, body };
45+
}, [world.workspace.workspaceId, world.engine]), { awaitPromise: true }),
46+
};
47+
}

0 commit comments

Comments
 (0)